How to Expose a Docker Port – Tutorial with Examples

How to Expose a Docker Port – Tutorial with Examples

When working with Docker, exposing ports is essential for enabling communication between your containerized application and the outside world. Whether you're running a web server, a database, or a custom app, knowing how to expose Docker ports is a fundamental skill.

Hi, I’m Deepak! In today’s blog, we’ll learn how to expose Docker ports, why it’s important, and explore some practical examples. Let’s get started!


What Does Exposing a Port Mean?

Exposing a Docker port makes the application running inside a container accessible to the host machine or other networked systems. By mapping a container port to a host port, you enable external access to your containerized service.


How to Expose a Docker Port

Docker ports can be exposed in two primary ways:

1. Expose Ports in the Dockerfile

You can specify the ports your application uses by adding the EXPOSE instruction in your Dockerfile.

#Docker File by Deepak
FROM nginx  
EXPOSE 80

2. Expose Ports During Container Run

You can map a container port to a host port using the -p or --publish flag during docker run.

docker run -d -p 8080:80 nginx

In this command:

  • 80 is the container’s port.

  • 8080 is the host machine’s port.


Examples

Example 1: Running an Nginx Container

  1. Run an Nginx container and expose port 80 to host port 8080:

     #run docker container with port
     docker run -d -p 8080:80 nginx
    
  2. Open a browser and navigate to http://localhost:8080 to see the Nginx welcome page.

Image Suggestion:

  • Screenshot of the Nginx welcome page in a browser.

Example 2: Exposing Multiple Ports

If your application uses multiple ports, you can map them as follows:

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

This maps:

  • Port 80 in the container to 8080 on the host.

  • Port 443 in the container to 8443 on the host.

Image Suggestion:

  • Diagram showing a container with two exposed ports connected to corresponding host ports.

Example 3: Using docker-compose to Expose Ports

For multi-container setups, use docker-compose.yml:

version: '3'  
services:  
  web:  
    image: nginx  
    ports:  
      - "8080:80"

Run the services with:

docker-compose up

Image Suggestion:

  • A visual representation of the docker-compose.yml structure.

Best Practices for Exposing Ports

  1. Avoid Exposing Unnecessary Ports
    Only expose the ports your application needs for security reasons.

  2. Use Firewalls or Network Policies
    Protect exposed ports with proper firewalls or security groups.

  3. Document Port Mappings
    Maintain a clear record of which ports are mapped for easier troubleshooting.


Created by Deepak Nemade