Port mapping in Docker
When mapping ports in docker you may run a command like:
docker run -it -p 5432:5432 docker-image-name
you might get an error such as: `docker: Error response from daemon: driver failed programming external connectivity on endpoint zen_davinci: Error starting userland proxy: listen tcp4 0.0.0.0:5432: bind: address already in use.`
This shows that port 5432:5432 can cannot be used since it is already being used by another service say PostgreSQL. To verify run:
sudo lsof -i 5432 .
You can change the mapping from 5432:5432 to 5433:5432 , showing how docker manages traffic from host machine and docker container. The format for port mapping is host_port:container_port.
5433(host port): This is the port on the host machine that will receive incoming traffic. Users can access services running inside the container via this port.5432(container port): This is the port inside the Docker container where the application is listening.
By changing the host port to 5433, you avoid conflicts with other services already using 5432.
Port Mapping in Docker Compose
If you’re using Docker Compose, you can specify port mappings directly in the docker-compose.yml file. Here’s an example:
Get Musyoki Kiilu’s stories in your inbox
Join Medium for free to get updates from this writer.
ports:
— “5433:5432”
version: '3.9'
services:
postgres:
image: postgres:latest
environment:
- POSTGRES_USER=root
- POSTGRES_PASSWORD=root
- POSTGRES_DB=ny_taxi
volumes:
- "./ny_taxi_postgres_data:/var/lib/postgresql/data:rw"
healthcheck:
test: ["CMD", "pg_isready","-U","root"]
interval: 5s
timeout: 30s
retries: 5
start_period: 30s
ports:
- "5433:5432"With Docker Compose, you can easily manage multiple container configurations and map ports as required. This is especially useful for defining configurations in complex, multi-container setups where containers depend on each other.
Using Bind Addresses to Avoid Conflicts
When binding ports, Docker defaults to 0.0.0.0, which makes the container accessible on all network interfaces. However, if you want the service to be accessible only locally, you can specify 127.0.0.1 instead:
docker run -it -p 127.0.0.1:5432:5432 docker-image-nameUsing Docker’s Internal Network
For services that need to communicate only within Docker containers (not accessible from the host), it’s best to use Docker’s internal networking instead of exposing ports.
For example, when running a multi-container setup with Docker Compose, containers can communicate via service names without exposing ports. Here’s an example configuration:
services:
app:
image: your-app-image
depends_on:
- db
db:
image: postgres
environment:
POSTGRES_PASSWORD: example
networks:
- internal_network
networks:
internal_network:
driver: bridgeIn this setup, the app container can connect to the db container using the service name db on port 5432, without needing to expose 5432 to the host.






