Port Binding
When a container is created, by default in Docker, all Docker containers have a port bound to them. Each container also has a separate virtual file system — we already saw that the files inside a container are separate from the host machine. Similarly, the ports of a container are also separate from the host machine.
For example, if we have a host machine with ports like 8080, 5000, etc., and we have a Docker container, that container also has some ports bound to it by default (like 3306 for MySQL). But these container ports are not the ports of the host machine (Mac OS) — they are the container's own ports.
However, we can bind the host machine's port with the container's port. Whenever we want a request coming to a specific port on our host to be forwarded to a specific port on our container, we use the -p flag:
docker run -d -p <host-port>:<container-port> mysql
Example
docker run -d -p 8080:3306 mysql
This binds the host machine's port 8080 with the container's port 3306.
This mapping process is called Port Binding.
Important Note
If we try to bind the same host port to two different containers, we will get an error:
Binding for 8080 failed because port is already allocated
Port 8080 is the host machine's port. Once it is bound to one container, the same port cannot be bound to another container.
For the second container, we must use a different host port:
# First container
docker run -d -p 8080:3306 --name mysql-latest mysql
# Second container — must use different host port
docker run -d -p 5000:3306 --name mysql-older mysql:8.0
So the container ports may be the same (3306), but the host machine ports must be different.
Troubleshoot Commands
When we run Docker containers, errors may occur in between. To check these errors, there are some troubleshoot commands we can run.
docker logs — Checking Container Logs
docker logs <container-name-or-id>
This gives us access to all the logs of a specific container, which can help us identify issues.
These logs can also be accessed in Docker Desktop by simply clicking on the container name.
docker exec — Running Commands on a Running Container
The exec command basically allows us to run additional commands on an already running container:
docker exec -it <container-name> /bin/bash
This opens the container's bash/shell in interactive mode.
By accessing the terminal of the container, we can:
- Check environment variables
- Check files
- Check different dependencies the container has
Example
docker exec -it mysql-latest /bin/bash
ls # List files
env # Check environment variables — root password visible here
exit # Exit
When we exit from exec, it does not stop our Docker container.
The container is still running — we just came out of the interactive bash shell.