I am new in Docker and Mongodb. I have a mongodb container with a database and collection. I created another container with php and apache using following command:
docker run -d -p 8020:80 --name my-php-apache php:7-apache
In order to be able to connect to mongodb container (my-mongo), i need to link this container to mongodb container. So i used following command to link both containers:
docker run -d -p 8020:80 --link my-mongo --name php-mongo-link php:7-apache
But it shows following error:
b36e400bb5c0d229f952a7b365d5a8bfed402410bdb5a802f29fd2fdc1ef28f9
docker: Error response from daemon: driver failed programming external connectivity on endpoint php-mongo-link (ec4eb66d0a314201c99f79eb4a09cf82ffb2fc399647020adaf34932878857b7): Bind for 0.0.0.0:8020 failed: port is already allocated.
To link the containers, should the ports of php-apache (8020:80) and php-mongo-link be same ? Or should they be different ? Is there any better way to link 2 containers (php-apache and mongodb) ? I just need to connect from the php container to the mongodb container to insert some data in the mongodb database.
3
Answers
You hand bind both containers to the same port on your host maschine. Both are bind to port 80. You should use another port for the second container like 81.
The issue is that you expose both container on the same port
8020
, so one must listen on8021
.extract from https://docs.docker.com/engine/reference/commandline/run/
You shouldn’t be using
docker run --link
at all on modern Docker. You need to create a Docker network (default settings are just fine) and then run both containers attached to that network. The containers will be able to reach each other using the--name
of the container as a host name.(If you use Docker Compose, it does this setup automatically.)
Every time you
docker run
something it creates a new container. A link is a property of a container that allows it to connect to a specific other container, in the networking model that existed before Docker 1.0; you need to specify it when you start the first container. In your example you’re running a container, then running a second copy of it with the link setting; you’re getting a conflict because both containers publish the same host port (-p 8020:...
). If you were to use--link
it would be on the firstdocker run
command, and you wouldn’t need a second one.