Movatterモバイル変換


[0]ホーム

URL:


Contact support
Contact support
Manuals

Legacy container links

Page options

Warning

The--link flag is a legacy feature of Docker. It may eventuallybe removed. Unless you absolutely need to continue using it, we recommend that you useuser-defined networks to facilitate communication between two containers instead of using--link. One feature that user-defined networks do not support that you can dowith--link is sharing environment variables between containers. However,you can use other mechanisms such as volumes to share environment variablesbetween containers in a more controlled way.

SeeDifferences between user-defined bridges and the default bridgefor some alternatives to using--link.

The information in this section explains legacy container links within theDocker defaultbridge network which is created automatically when you installDocker.

Before theDocker networks feature, you could use theDocker link feature to allow containers to discover each other and securelytransfer information about one container to another container. With theintroduction of the Docker networks feature, you can still create links but theybehave differently between defaultbridge network anduser defined networks.

This section briefly discusses connecting via a network port and then goes intodetail on container linking in defaultbridge network.

Connect using network port mapping

Let's say you used this command to run a simple Python Flask application:

$ docker run -d -P training/webapp python app.py

When that container was created, the-P flag was used to automatically mapany network port inside it to a random high port within anephemeral portrange on your Docker host. Next, whendocker ps was run, you saw that port5000 in the container was bound to port 49155 on the host.

$ docker ps nostalgic_morseCONTAINER ID  IMAGE                   COMMAND       CREATED        STATUS        PORTS                    NAMESbc533791f3f5  training/webapp:latest  python app.py 5 seconds ago  Up 2 seconds  0.0.0.0:49155->5000/tcp  nostalgic_morse

You also saw how you can bind a container's ports to a specific port usingthe-p flag. Here port 80 of the host is mapped to port 5000 of thecontainer:

$ docker run -d -p 80:5000 training/webapp python app.py

And you saw why this isn't such a great idea because it constrains you toonly one container on that specific port.

Instead, you may specify a range of host ports to bind a container port tothat is different than the defaultephemeral port range:

$ docker run -d -p 8000-9000:5000 training/webapp python app.py

This would bind port 5000 in the container to a randomly available portbetween 8000 and 9000 on the host.

There are also a few other ways you can configure the-p flag. Bydefault the-p flag binds the specified port to all interfaces onthe host machine. But you can also specify a binding to a specificinterface, for example only to thelocalhost.

$ docker run -d -p 127.0.0.1:80:5000 training/webapp python app.py

This would bind port 5000 inside the container to port 80 on thelocalhost or127.0.0.1 interface on the host machine.

Or, to bind port 5000 of the container to a dynamic port but only on thelocalhost, you could use:

$ docker run -d -p 127.0.0.1::5000 training/webapp python app.py

You can also bind UDP and SCTP (typically used by telecom protocols such as SIGTRAN, Diameter, and S1AP/X2AP) ports by adding a trailing/udp or/sctp. For example:

$ docker run -d -p 127.0.0.1:80:5000/udp training/webapp python app.py

You also learned about the usefuldocker port shortcut which showed us thecurrent port bindings. This is also useful for showing you specific portconfigurations. For example, if you've bound the container port to thelocalhost on the host machine, then thedocker port output reflects that.

$ docker port nostalgic_morse5000127.0.0.1:49155
Note

The-p flag can be used multiple times to configure multiple ports.

Connect with the linking system

Note

This section covers the legacy link feature in the defaultbridge network.Refer todifferences between user-defined bridges and the default bridgefor more information on links in user-defined networks.

Network port mappings are not the only way Docker containers can connect to oneanother. Docker also has a linking system that allows you to link multiplecontainers together and send connection information from one to another. Whencontainers are linked, information about a source container can be sent to arecipient container. This allows the recipient to see selected data describingaspects of the source container.

The importance of naming

To establish links, Docker relies on the names of your containers.You've already seen that each container you create has an automaticallycreated name; indeed you've become familiar with our old friendnostalgic_morse during this guide. You can also name containersyourself. This naming provides two useful functions:

  1. It can be useful to name containers that do specific functions in a waythat makes it easier for you to remember them, for example naming acontainer containing a web applicationweb.

  2. It provides Docker with a reference point that allows it to refer to othercontainers, for example, you can specify to link the containerweb to containerdb.

You can name your container by using the--name flag, for example:

$ docker run -d -P --name web training/webapp python app.py

This launches a new container and uses the--name flag toname the containerweb. You can see the container's name using thedocker ps command.

$ docker ps -lCONTAINER ID  IMAGE                  COMMAND        CREATED       STATUS       PORTS                    NAMESaed84ee21bde  training/webapp:latest python app.py  12 hours ago  Up 2 seconds 0.0.0.0:49154->5000/tcp  web

You can also usedocker inspect to return the container's name.

Note

Container names must be unique. That means you can only callone containerweb. If you want to re-use a container name you must deletethe old container (withdocker container rm) before you can create a newcontainer with the same name. As an alternative you can use the--rmflag with thedocker run command. This deletes the containerimmediately after it is stopped.

Links allow containers to discover each other and securely transfer informationabout one container to another container. When you set up a link, you create aconduit between a source container and a recipient container. The recipient canthen access select data about the source. To create a link, you use the--linkflag. First, create a new container, this time one containing a database.

$ docker run -d --name db training/postgres

This creates a new container calleddb from thetraining/postgresimage, which contains a PostgreSQL database.

Now, you need to delete theweb container you created previously so you can replace itwith a linked one:

$ docker container rm -f web

Now, create a newweb container and link it with yourdb container.

$ docker run -d -P --name web --link db:db training/webapp python app.py

This links the newweb container with thedb container you createdearlier. The--link flag takes the form:

--link <name or id>:alias

Wherename is the name of the container we're linking to andalias is analias for the link name. That alias is used shortly.The--link flag also takes the form:

--link <name or id>

In this case the alias matches the name. You could write the previousexample as:

$ docker run -d -P --name web --link db training/webapp python app.py

Next, inspect your linked containers withdocker inspect:

$ docker inspect -f"{{ .HostConfig.Links }}" web[/db:/web/db]

You can see that theweb container is now linked to thedb containerweb/db. Which allows it to access information about thedb container.

So what does linking the containers actually do? You've learned that a link allows asource container to provide information about itself to a recipient container. Inour example, the recipient,web, can access information about the sourcedb. To dothis, Docker creates a secure tunnel between the containers that doesn't need toexpose any ports externally on the container; when we started thedb container we did not use either the-P or-p flags. That's a big benefit oflinking: we don't need to expose the source container, here the PostgreSQL database, tothe network.

Docker exposes connectivity information for the source container to therecipient container in two ways:

  • Environment variables,
  • Updating the/etc/hosts file.

Environment variables

Docker creates several environment variables when you link containers. Dockerautomatically creates environment variables in the target container based onthe--link parameters. It also exposes all environment variablesoriginating from Docker from the source container. These include variables from:

  • theENV commands in the source container's Dockerfile
  • the-e,--env, and--env-file options on thedocker runcommand when the source container is started

These environment variables enable programmatic discovery from within thetarget container of information related to the source container.

Warning

It is important to understand that all environment variables originatingfrom Docker within a container are made available to any containerthat links to it. This could have serious security implications if sensitivedata is stored in them.

Docker sets an<alias>_NAME environment variable for each target containerlisted in the--link parameter. For example, if a new container calledweb is linked to a database container calleddb via--link db:webdb,then Docker creates aWEBDB_NAME=/web/webdb variable in theweb container.

Docker also defines a set of environment variables for each port exposed by thesource container. Each variable has a unique prefix in the form<name>_PORT_<port>_<protocol>

The components in this prefix are:

  • the alias<name> specified in the--link parameter (for example,webdb)
  • the<port> number exposed
  • a<protocol> which is either TCP or UDP

Docker uses this prefix format to define three distinct environment variables:

  • Theprefix_ADDR variable contains the IP Address from the URL, forexampleWEBDB_PORT_5432_TCP_ADDR=172.17.0.82.
  • Theprefix_PORT variable contains just the port number from the URL ofexampleWEBDB_PORT_5432_TCP_PORT=5432.
  • Theprefix_PROTO variable contains just the protocol from the URL ofexampleWEBDB_PORT_5432_TCP_PROTO=tcp.

If the container exposes multiple ports, an environment variable set isdefined for each one. This means, for example, if a container exposes 4 portsthat Docker creates 12 environment variables, 3 for each port.

Additionally, Docker creates an environment variable called<alias>_PORT.This variable contains the URL of the source container's first exposed port.The 'first' port is defined as the exposed port with the lowest number.For example, consider theWEBDB_PORT=tcp://172.17.0.82:5432 variable. Ifthat port is used for both tcp and udp, then the tcp one is specified.

Finally, Docker also exposes each Docker originated environment variablefrom the source container as an environment variable in the target. For eachvariable Docker creates an<alias>_ENV_<name> variable in the targetcontainer. The variable's value is set to the value Docker used when itstarted the source container.

Returning back to our database example, you can run theenvcommand to list the specified container's environment variables.

$ docker run --rm --name web2 --link db:db training/webapp env<...>DB_NAME=/web2/dbDB_PORT=tcp://172.17.0.5:5432DB_PORT_5432_TCP=tcp://172.17.0.5:5432DB_PORT_5432_TCP_PROTO=tcpDB_PORT_5432_TCP_PORT=5432DB_PORT_5432_TCP_ADDR=172.17.0.5<...>

You can see that Docker has created a series of environment variables withuseful information about the sourcedb container. Each variable is prefixedwithDB_, which is populated from thealias you specified above. If thealiasweredb1, the variables would be prefixed withDB1_. You can use theseenvironment variables to configure your applications to connect to the databaseon thedb container. The connection is secure and private; only thelinkedweb container can communicate with thedb container.

Important notes on Docker environment variables

Unlike host entries in the/etc/hosts file,IP addresses stored in the environment variables are not automatically updatedif the source container is restarted. We recommend using the host entries in/etc/hosts to resolve the IP address of linked containers.

These environment variables are only set for the first process in thecontainer. Some daemons, such assshd, scrub them when spawning shellsfor connection.

Updating the/etc/hosts file

In addition to the environment variables, Docker adds a host entry for thesource container to the/etc/hosts file. Here's an entry for thewebcontainer:

$ docker run -t -i --rm --link db:webdb training/webapp /bin/bashroot@aed84ee21bde:/opt/webapp# cat /etc/hosts172.17.0.7  aed84ee21bde<...>172.17.0.5  webdb 6e5cdeb2d300 db

You can see two relevant host entries. The first is an entry for thewebcontainer that uses the Container ID as a host name. The second entry uses thelink alias to reference the IP address of thedb container. In addition tothe alias you provide, the linked container's name, if unique from the aliasprovided to the--link parameter, and the linked container's hostname arealso added to/etc/hosts for the linked container's IP address. You can pingthat host via any of these entries:

root@aed84ee21bde:/opt/webapp# apt-get install -yqq inetutils-pingroot@aed84ee21bde:/opt/webapp# ping webdbPING webdb (172.17.0.5): 48 data bytes56 bytes from 172.17.0.5: icmp_seq=0 ttl=64 time=0.267 ms56 bytes from 172.17.0.5: icmp_seq=1 ttl=64 time=0.250 ms56 bytes from 172.17.0.5: icmp_seq=2 ttl=64 time=0.256 ms
Note

In the example, you had to installping because it was not includedin the container initially.

Here, you used theping command to ping thedb container using its host entry,which resolves to172.17.0.5. You can use this host entry to configure an applicationto make use of yourdb container.

Note

You can link multiple recipient containers to a single source. Forexample, you could have multiple (differently named) web containers attached to yourdb container.

If you restart the source container, the/etc/hosts files on the linked containersare automatically updated with the source container's new IP address,allowing linked communication to continue.

$ docker restart dbdb$ docker run -t -i --rm --link db:db training/webapp /bin/bashroot@aed84ee21bde:/opt/webapp# cat /etc/hosts172.17.0.7  aed84ee21bde<...>172.17.0.9  db

Edit this page

Request changes


[8]ページ先頭

©2009-2025 Movatter.jp