Docker

How to Forward Port in Docker

Docker is a well-liked dockerization platform that dockerizes applications and software in an isolated environment known as a container. While executing applications in containers, users are usually required to access the containerized application outside the container. For this purpose, users need to apply the port forwarding technique.

Port forwarding in Docker is a process that enables us to expose the container port on the Docker host system. It permits us to run the application in an isolated environment and also make it accessible from outside the container on a user machine.

This post will demonstrate:

How to Forward Port in Docker Using “-p” or “–publish” Tag

To forward a port in Docker, the user needs to publish the container port on the Docker host. For this purpose, run the container on the docker host using the “-p” or “–publish” tag in the “docker run” command.

For proper demonstration, follow the below instructions.

Step 1: Make Dockerfile

First, create a file and set its name as “Dockerfile”. This file contains the textual instructions to create the template of the Docker container. For instance, let’s dockerize the simple Golang program using the below snippet in the Dockerfile:

FROM golang:1.8

WORKDIR /go/src/app

COPY main2.go .

RUN go build -o webserver .

EXPOSE 8080

CMD ["./webserver"]

In the given snippet:

  • FROM” command is utilized to set the base image.
  • WORKDIR” defines the container’s working directory.
  • COPY” command will create a copy of the program file in the container-specified path.
  • RUN” command will execute the specified command in the container.
  • EXPOSE” command specifies the port where the container will be listened to.
  • CMD” specifies the executable points of the container.

Step 2: Create a Golang Program

Next, create another file named “main2.go” and paste the below provided Golang program that prints a simple string on port “8080”:

package main

import (

  "fmt"

  "log"

  "net/http"

)

func handler(w http.ResponseWriter, r *http.Request) {

html := `

  <!DOCTYPE html>

  <html>

  <head>

    <title>Hello Golang!</title>
 
    <style>

    body {

        background-color: #D2B48C;

    }

    .container {

        text-align: center;

         padding: 50px;

    }

  </style>

  </head>

  <body>

    <div class="container">

    <h1>Hello! Welcome to LinuxHint Tutorial</h1>

    </div>

  </body>

  </html>`

w.Header().Set("Content-Type", "text/html")

fmt.Fprint(w, html)

}

func main() {

http.HandleFunc("/", handler)

log.Fatal(http.ListenAndServe("0.0.0.0:8080", nil))

}

Step 3: Generate Container’s Snapshot

Now, generate a snapshot for the container from the above specified Dockerfile. For this purpose, first, navigate to the directory where the Dockerfile is created using the “cd <path-to-working-dir>” command:

Next, generate the new container image using the given command:

docker build -t golang-img .

The given result shows that the image is created according to the provided build context.

Step 4: Forward Host Port to Container Port

Now, execute the container and forward the host port to the container port to access the dockerize app outside the container on a local machine. For this purpose, run the “docker run –name <cont-name> -p <host-port>:<cont-port> <image-name>” command:

docker run --name go-cont -p 8080:8080 golang-img

Here, the “-p” flag is utilized to publish the container executing port on the docker host:

Step 5: Verification

For verification, view the running containers using “docker ps”:

docker ps

In the below result, the containerized application is listening on available network interfaces “0.0.0.0” on published port “8080”. It implies that the port is forwarded to the running application on the host machine:

Now, launch the browser and navigate to “http://localhost:8080/” and verify whether the port forwarding technique is applied or not and if the containerized application is accessible outside the container on the host system:

Here we have successfully forwarded the host port to the container port and the application is accessible on the docker host.

How to Forward Port in Docker Using Docker Compose

To forward the container port to the host to access the containerized application from outside the container, the user can utilize the “port” key in the compose yaml file. Docker compose is a Docker service that enables us to run different services and applications in different containers. Using the “docker-compose.yml” file, the user can also forward the container port to the host machine and have an application connection to the outside world.

Check out the below procedure for illustrations.

Step 1: Make Compose File

First, generate a file named “docker-compose.yml” file and add the following content to the file:

version: "3"

services:

web:

build: .

ports:

- 8080:8080

In the above snippet, the “ports” key is used to connect the host to the container port. Here, the first value is the host port, and the second value is the container port.

Step 2: Launch App

After specifying the instructions in the compose file, launch the application in a container using the “docker-compose up” command:

docker-compose up

Step 3: Verification

For verification, list down the compose containers using the “docker-compose ps” command:

docker-compose ps -a

To check if the container is accessible on the host machine, navigate to the “http://localhost:8080/” URL. Here, you can see we have effectively forwarded the container port on the host:

How to Forward Port to Specific Network

To forward a container port to a specific network, the user needs to specify the network on which they want to access the container using the “–network” option. Look at the given steps for demonstration.

Step 1: Create a Network

Create a new network using the “docker network create <net-name>” command. By default, this network will use a bridge driver:

docker network create mygo-network

To view the Docker networks, utilize the “docker network ls” command:

docker network ls

Here, we have successfully created “mygo-network” that is using “bridge” driver:

Step 2: Map Network

To run and access the container on the specific network using the port forwarding technique, use the below command:

docker run -p 8080:8080 --network mygo-network golang-img

In the given command, the “-p” option publishes the container on a specified port of the specified network. Here, the “–network” option is used to define the docker network:

For verification, again navigate to the “http://localhost:8080” port and check if the container is accessible on the specified network or not:

The above output indicates that we have effectively forwarded the container port on a specific network.

Note: While using the “host” network, the user does not need to publish the port from container to host using the “-p” or “–publish” option.

Forward Port to Specific Network Using Docker Compose

Add the following snippet in the “docker-compose.yml” file. In the below snippet, the “networks” key is used to specify the network:

version: "3"
services:
   
  web:
    build: .
    ports:
    - 8080:8080

Now, launch the application in a container using the “docker-compose up” command:

docker-compose up

We have covered the methods for port forwarding in Docker.

Conclusion

To forward the port in Docker for accessing the dockerize application outside the container, the user can either use the “-p” or “–publish” option in the “docker run” command or the user can use the “ports” key in Docker compose file. In order to access the container on a specific network, the user can forward the container port on a network by using the “–network <network>” option. This blog has demonstrated the techniques to forward ports in Docker.

About the author

Rafia Zafar

I am graduated in computer science. I am a junior technical author here and passionate about Programming and learning new technologies. I have worked in JAVA, HTML 5, CSS3, Bootstrap, and PHP.