How to link containers?
How to link containers?
To link Docker containers, you can use the legacy --link
flag or modern Docker networking features. Here’s a detailed explanation of both methods:
--link
FlagThe --link
flag is a legacy feature that allows you to link multiple containers together, enabling them to share information securely. Here’s how you can link containers using this method:
Create the Source Container:
First, create a container that will act as the source. For example, a PostgreSQL database container:
$ docker run -d --name db training/postgres
Remove the Existing Recipient Container:
If you have an existing container that you want to link, remove it first:
$ docker container rm -f web
Create and Link the Recipient Container:
Create a new container and link it to the source container using the --link
flag:
$ docker run -d -P --name web --link db:db training/webapp python app.py
In this command, --link db:db
links the web
container to the db
container, allowing web
to access information about db
.
Inspect the Link:
You can inspect the link to verify the connection:
$ docker inspect -f "{{ .HostConfig.Links }}" web
This should show the link between the web
and db
containers.
Accessing Linked Container Information:
The recipient container can access the source container’s information via environment variables and the /etc/hosts
file. For example, the web
container can access the db
container’s IP address and other details without exposing ports externally[1][4].
Modern Docker networking provides more flexible and powerful ways to connect containers. Here’s how you can achieve container communi...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào