Docker Tutorial

15. Docker Managing Ports | Expose and Map Container Ports

Docker – Managing Ports

Managing ports in Docker allows containers to communicate with the host system or the outside world. By default, containers are isolated, so you need to explicitly map container ports to host ports to enable access.

Port Mapping Basics

Docker uses the -p or --publish option to map container ports to host ports. This allows external systems to reach services running inside the container.


# Run a container and map container port 80 to host port 8080
docker run -d -p 8080:80 nginx

# Access the container service via http://localhost:8080

Specifying IP Address for Port Mapping

You can bind container ports to a specific host IP to control access:


# Bind container port 80 to host IP 192.168.1.100 port 8080
docker run -d -p 192.168.1.100:8080:80 nginx

Mapping Multiple Ports

Containers can expose multiple ports at once. You can map each required port individually:


docker run -d -p 8080:80 -p 8443:443 nginx

Using EXPOSE in Dockerfile

The EXPOSE instruction in a Dockerfile declares which ports the container will use. Note that EXPOSE alone does not publish the ports to the host; it’s mainly documentation for users and tools.


# Dockerfile example
FROM nginx
EXPOSE 80
EXPOSE 443

Best Practices for Managing Ports

  • Map only necessary ports to minimize security risks.
  • Use non-default host ports if multiple containers expose the same container port.
  • Document all port mappings for team clarity.
  • Use firewall rules or network policies to control access to exposed ports.
  • Use Docker Compose for consistent port mapping across multi-container apps.

Conclusion

Managing ports correctly ensures your Docker containers communicate efficiently with the host and external networks while maintaining security. Proper port mapping is essential for both development and production environments.

Leave a Reply

Your email address will not be published. Required fields are marked *