Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker link container as build argument

I've a Docker composer file similar to:

version: '2'
services:
    db:
        image: mariadb:10.1
        volumes:
            - "./.data/db:/var/lib/mysql"
        restart: always
        environment:
            MYSQL_ROOT_PASSWORD: test
            MYSQL_DATABASE: test
            MYSQL_USER: test
            MYSQL_PASSWORD: test
    test:
        depends_on:
            - db
        links:
            - db:db
        build:
            context: .
            args:
                MYSQL_HOST: db
                MYSQL_DATABASE: test
                MYSQL_USER: test
                MYSQL_PASSWORD: test
        ports:
            - "8000:80"
        restart: always

Inside test container Dockerfile

FROM ...

...
ARG MYSQL_HOST 127.0.0.1

RUN set -x; echo $MYSQL_HOST

RUN script ... --param $MYSQL_HOST

However MYSQL_HOST variable (which I would expect to be the internal IP of the other container) is not being translated into the other container name.

How could it be done? Can it be achieved in another way with docker-compose?

like image 789
Toni Hermoso Pulido Avatar asked Jun 16 '26 05:06

Toni Hermoso Pulido


1 Answers

I don't think you want a build argument here. Would probably set MYSQL_HOST as an environment variable. Inside of docker-compose, the literal string db is actually resolvable to your db container.

Typically, compose files look like this:

test:
   links:
     db:db
   environment:
     - MYSQL_HOST=db

Then in your test code do something like:

...
String dbHost = System.getEnv("MYSQL_HOST");
...

That way, the MySql host doesn't need to be built into your image removing the need for your image to be rebuilt all the time.

like image 179
Russell Cohen Avatar answered Jun 21 '26 12:06

Russell Cohen