Debug School

rakesh kumar
rakesh kumar

Posted on

How to expose multiple containers on different ports using port forwarding

Port forwarding in Docker allows you to expose ports from a Docker container to the host machine or to other containers. It plays a crucial role in making services inside containers accessible from outside the container or from other containers. Here's an explanation with an example and expected output:

Image description

Image description

Image description

Example: Run a Simple Web Server in a Docker Container
Let's use a simple example with the Nginx web server. We'll run an Nginx container, expose its internal port 80 to the host machine's port 8080, and access the web server from a web browser.

Step 1: Run Nginx Container

docker run -d -p 8080:80 --name my-nginx nginx
Enter fullscreen mode Exit fullscreen mode

-d: Run the container in detached mode.
-p 8080:80: Map port 8080 on the host to port 80 on the container.
--name my-nginx: Assign a custom name to the container.
nginx: The name of the Docker image.
Step 2: Verify Container Status

docker ps
Enter fullscreen mode Exit fullscreen mode

Output should show the running container:

Image description

Step 3: Access Nginx in a Web Browser
Open a web browser and navigate to http://localhost:8080. You should see the default Nginx welcome page.

The -p option in the docker run command specifies port forwarding. It maps the host's port to the container's port.
In this example, we mapped port 8080 on the host ( to port 80 on the Nginx container (80/tcp).
The web server running inside the Nginx container is now accessible from the host machine on http://localhost:8080.
Important Notes:
Port forwarding allows you to expose multiple containers on different ports.
You can also bind containers to specific network interfaces or IP addresses.
Always be mindful of security considerations when exposing ports, and avoid using default or well-known ports for security reasons.
Port forwarding is a fundamental feature in Docker that facilitates communication between containers and the host machine or other external systems. It enables you to run and access services within Docker containers easily.

Top comments (0)