Maen
Maen

Reputation: 10698

Pass container IP across containers for config file

I'm new to Docker, and am attempting to create two containers, one for MySQL and one for my Node.js app, based on images from Docker's HUB.

I'd like to connect my node app to the MySQL host.

For this, I'm planning to store informations about this host through environment variables in my config.yaml (used by node-config) for later use.

My question is : how could I pass the IP address of the MySQL container to my node.js app?

It is dynamically attributed, I vaguely know I can retrieve it with a command as docker inspect $(docker ps -q) | grep '"IPAddress"', it may be a clue?


Docker-compose.yml :

mysql:
  image: mysql:5.6
  environment:   
    - MYSQL_ROOT_PASSWORD=****
    - MYSQL_DATABASE=database
    - MYSQL_USER=user
    - MYSQL_PASSWORD=****
  volumes:
    - /data/mysql:/var/lib/mysql

nodeapp:
  build: .
  environment:
    - MYSQL_USER=^^^^^ // will mirror the value up there, and so on
    - ...
  ports:
    - "80:3000"
  links:
    - mysql

Config.yaml :

app:

  port: 3000

  db:
    host: "MYSQL_HOST" // How can this be dynamic ?
    port:"MYSQL_PORT"
    database: "MYSQL_DATABASE"
    user: "MYSQL_USER"
    password: "MYSQL_PASSWORD"

Dockerfile :

FROM    node:0.10

ADD package.json /usr/src/package.json
# Install app dependencies
RUN cd /usr/src && npm install

ADD . /usr/src
WORKDIR /usr/src

EXPOSE  3000

CMD npm start

Upvotes: 0

Views: 1132

Answers (1)

nessuno
nessuno

Reputation: 27050

When you run containers with docker-compose, it adds in every container in /etc/hosts a dynamic line with the format

<dynamic ip> container_name

Thus, when you run docker-compose up every container knows any other container by its name.

So, in your confing.yaml you have to change this line

 host: "MYSQL_HOST" // How can this be dynamic ?

with

host: mysql

since in /etc/hosts you have the dynamic association between the hostname mysql and the dynamic ip assigned by docker the the MySQL container.

Upvotes: 2

Related Questions