Docker Ports


Understanding Ports in Docker
When running multiple containers on a single host:
Host ports must be unique – Only one container can bind to a specific host port at a time.
Container ports can overlap – Different containers can use the same internal port (e.g., two apps using port
3000
inside their containers).
Port Mapping Syntax
To expose a container’s port to the host, use:
docker run -p <HOST_PORT>:<CONTAINER_PORT> ...
HOST_PORT
: Port on your machine (must be free).CONTAINER_PORT
: Port the app uses inside the container.
Example: Running PostgreSQL
docker run --name my_db \
-p 5432:5432 \ # Maps host:5432 → container:5432
-e POSTGRES_PASSWORD=password \
-v pg_data:/var/lib/postgresql/data \ #named_volume
-d postgres
Key Concepts
1. Detached Mode (-d
)
Runs the container in the background (like a daemon).
Without
-d
: The container ties up your terminal.With
-d
: Frees your terminal; usedocker logs <container>
to view output.
2. Testing Connections (Without IntelliJ Database Tab)
Option 1: Command Line (PSQL)
psql -h localhost -p 5432 -U postgres
Option 2: GUI Tools
DBeaver (Free)
TablePlus (Paid, free trial)
PgAdmin (For PostgreSQL)
3. Stopping/Removing Containers
Stop a running container:
docker stop my_db
Remove a stopped container:
docker rm my_db
Force remove (running container):
docker rm -f my_db
PS: You can’t remove a running container
Common Pitfalls & Solutions
"Port Already in Use" Error
Cause: Another service (or container) is using the host port.
Fix:
Change the host port (e.g.,
-p 5433:5432
).Stop the conflicting service:
sudo lsof -i :5432 # Find PID kill -9 <PID> # Terminate
Firewall Blocking Connections
On Linux/macOS:
sudo ufw allow 5432/tcp
On Windows: Adjust inbound rules in Windows Defender Firewall.
Best Practices
Use named volumes (as shown above) for persistent data.
Avoid running as root inside containers for security:
docker run --user 1000:1000 ...
Limit memory usage to prevent host exhaustion:
docker run -m 512m ...
Recap: Key Commands
Purpose | Command |
Run a container | docker run -p 80:80 -d nginx |
List running containers | docker ps |
Stop a container | docker stop <name> |
Remove a container | docker rm <name> |
View logs | docker logs -f <name> |
Subscribe to my newsletter
Read articles from Phenny Mwaisaka directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by