Use --link to connect containers on the default bridge network (legacy; user-defined networks with DNS are preferred on modern Docker).
docker run --link CONTAINER:ALIAS ...
CONTAINER— name of the target container.ALIAS— hostname used inside the new container to reach the target.
/etc/hosts
With links, Docker adds the target container’s name and ID to /etc/hosts in the new container so you can resolve it by name.
Environment variables
Docker injects environment variables into the new container to describe the linked service. Example:
docker run -d --name myredis redis
docker run --link myredis:andrew debian env
Sample output:
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=19abfc4523ff
ANDREW_PORT=tcp://172.17.0.2:6379
ANDREW_PORT_6379_TCP=tcp://172.17.0.2:6379
ANDREW_PORT_6379_TCP_ADDR=172.17.0.2
ANDREW_PORT_6379_TCP_PORT=6379
ANDREW_PORT_6379_TCP_PROTO=tcp
ANDREW_NAME=/frosty_clarke/andrew
ANDREW_ENV_GOSU_VERSION=1.11
ANDREW_ENV_REDIS_VERSION=5.0.7
...
Variables prefixed with ANDREW_ENV_ are copied from the linked container’s environment. Do not store secrets in container env vars if you use links — they can leak through these variables.
Example
docker run --rm -it --link myredis:redis redis /bin/bash
The --link myredis:redis argument adds a redis entry in /etc/hosts pointing at myredis, so redis-cli can use the hostname redis directly.
Security
By default, containers on the same bridge can talk to each other even without an explicit link. To restrict this, start the daemon with --icc=false and --iptables. With inter-container communication disabled, Docker adds iptables rules so linked containers can only reach declared exposed ports on each other.
Related topics
- Networking — CNM, bridge driver, overlay
- Exposing containers — publish ports to the host
Andrew Dorokhov