Home > OS >  Docker - Bind for 0.0.0.0:3306 failed: port is already allocated
Docker - Bind for 0.0.0.0:3306 failed: port is already allocated

Time:12-04

When I run image "mysql" after my container I see this error "Bind for 0.0.0.0:3306 failed: port is already allocated". `it means I have something that uses port 3306.

After running this command,

docker container ls

I clearly see image "mysql/mysql-server:8.0" that uses 3306 port.

If I just delete it with this command,

docker rm -f <container-name>

I can run my"mysql" and everything works fine! But when I stop container and run again I see the same problem, because "mysql/mysql-server:8.0" uses 3306 again. How can I fix this, without removing this image every time running a container?

CodePudding user response:

If you want to run multiple containers on your machine that use the same port (in this case, port 3306), you'll need to use a feature called "port mapping" to map each container's port to a different host port. This will allow each container to use the same port internally, while still being accessible on different host ports.

To use port mapping, you'll need to use the -p or --publish option when starting your container, and specify a mapping between the container's port and the host port you want to use. For example, to map the mysql container's port 3306 to host port 3307, you could use the following command:

docker run -p 3307:3306 <image-name>

This would start the mysql container and map its port 3306 to host port 3307, allowing you to access the container on port 3307 on your host machine. You could then run another container that uses port 3306, and map that container's port 3306 to a different host port (e.g. 3308), allowing both containers to run simultaneously without conflict.

I hope this helps clarify how to use port mapping to run multiple containers that use the same port. Let me know if you have any other questions.

CodePudding user response:

When a container stops, Docker keeps it around in case you want to look at the logs or the contents of the container file system. If you don't need that and you want Docker to remove the container completely when it stops, you can add the --rm option to the docker run command, like this

docker run --rm -p 3306:3306 mysql

Then, when the container stop, Docker will remove it and free up port 3306, so you can use it again.

  • Related