Search code examples
dockerboot2dockerdockerfiledocker-compose

Linking my custom docker container to another custom container


I have two Rails docker containers:

The first is the the front-end application (container1) and the other is the backend API (container2).

The frontend can be access at http://0.0.0.0:3000. The front-end connects to the backend API via http://0.0.0.0:5000.

I have used this to start the frontend linking it to the backend

docker run --name=frontend --publish=3000:3000 --link=postgis:postgres --link=backend:backend --volume=/var/app:/app --tty=false --interactive=false --detach=true frontend

Backend is running as usual

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                            NAMES
cd4521524caf        backend             "/bin/bash -l -c /setu"   About an hour ago   Up About an hour    0.0.0.0:5000->5000/tcp                         backend

The linked backend I observed has added an entry in the /etc/hosts

172.17.0.712    cd4521524caf
127.0.0.1   localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.2  postgres 12b29087618e postgis

How can I get/expose the name and alias of my backend docker container to register properly in /etc/hosts and also how can I expose an environment variable that will have the value of 172.17.0.12:5000.

I noticed other docker containers (like postgis) that I have linked add environment variables but mine (backend) doesn't.

I would like my environment variable to be like

BACKEND_API="http://172.17.0.12:5000"

And the /etc/hosts entry to be:

172.17.0.712    backend cd4521524caf backend

Solution

  • If your software supports name resolution via /etc/hosts (which is very, very likely unless you're doing name resolution by hand in the frontend), you could just use -e BACKEND_API="http://backend:5000" and it will automatically pull the correct IP from /etc/hosts directly.