Docker Community Forums

Share and learn in the Docker community.

What is the correct way to link containers?


(Peterc) #1

When linking containers with docker compose I went looking for information on the environment variables available to me and found this notice:

Note: Environment variables are no longer the recommended method for connecting to linked services. Instead, you should use the link name (by default, the name of the linked service) as the hostname to connect to. See the docker-compose.yml documentation for details.

And, in fact, I don’t see any environment variables being set when I link containers with docker-compose. Also, when using docker-compose, the name of the service is dynamically generated. So how am I supposed to get the information to the linking container? I thought I would just explicitly name the container but see this in the documentation:

Because Docker container names must be unique, you cannot scale a service beyond 1 container if you have specified a custom name. Attempting to do so results in an error.

Makes sense, but then how do I get the container name where it needs to go? For now I’m explicitly passing it in an environment variable that I set but I think there must be a better way.

Here is the docker-compose.yml file that I’m using

version: '2'
services:
  web:
    image: nginx
    ports:
      - "80:80"
    volumes:
      - ./html:/var/www/html
    links:
      - php
    environment:
      PHP_HOST: php
  php:
    image: php-fpm
    volumes:
      - ./php:/var/www/php
    links:
      - db:db
    environment:
      DB_HOST: db
  db:
    image: mariadb
    ports:
      - "3306:3306"
    environment:
      MYSQL_ROOT_PASSWORD: password

This is working because I’m only starting one instance of these containers. Can anyone suggest a better, more robust way?


(Dvohra) #2

Environment variable is not required to be set. The links tag finds the specified service.

For example,
services:
web:
build: "."
command: "bundle exec rails s -p 3000 -b ‘0.0.0.0’"
links:
-
db
ports:
-
“3000:3000"
volumes:
-
”.:/rubyapp"
db:
image: mysql
environment:
-
MYSQL_ROOT_PASSWORD=mysql