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> mysqldocker run -d -p 8080:3306 mysqlThis binds the host machine's port 8080 with the container's port 3306.
This mapping process is called Port Binding.
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 allocatedPort 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.0So the container ports may be the same (3306), but the host machine ports must be different.
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 Logsdocker 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 ContainerThe exec command basically allows us to run additional commands on an already running container:
docker exec -it <container-name> /bin/bashThis opens the container's bash/shell in interactive mode.
By accessing the terminal of the container, we can:
docker exec -it mysql-latest /bin/bash
ls # List files
env # Check environment variables — root password visible here
exit # ExitWhen 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.