The cart is empty

Port forwarding is a crucial functionality for managing network communication of containers in Docker. In this article, we will focus on the specific procedure for setting up port forwarding for containers running on CentOS 7 without using Docker Compose. This approach is ideal for situations where you need to quickly forward ports without unnecessary complication or when Docker Compose is not available or suitable for the task at hand.

Prerequisites

Before you begin, make sure you have:

  • CentOS 7 installed
  • Docker installed
  • A user account with permissions to run Docker commands (typically root or a user in the docker group)

Step 1: Installing and Configuring firewalld

CentOS 7 uses firewalld as the default solution for firewall management. To set up port forwarding, you need to have firewalld installed and active.

  1. Install firewalld:

    sudo yum install firewalld
    
  2. Start firewalld:

    sudo systemctl start firewalld
    
  3. Configure firewalld to start automatically on boot:

    sudo systemctl enable firewalld
    

Step 2: Setting up Port Forwarding Rules in firewalld

Let's assume you want to forward all traffic from public port 80 to port 8080, where your Docker container is running.

  1. Add a forwarding rule:

    sudo firewall-cmd --zone=public --add-forward-port=port=80:proto=tcp:toport=8080
    
  2. Make the rule permanent:

    sudo firewall-cmd --runtime-to-permanent
    

Step 3: Running Docker Containers with Port Settings

Now that you have port forwarding set up at the system level, you can start a Docker container with the appropriate port settings.

  1. Run the container with port binding:
    sudo docker run -d -p 8080:8080 --name my_container <image>
    ​

In this example, -p 8080:8080 means Docker will BIND port 8080 on the host system to port 8080 in the container. <image> is the name of the Docker image you want to use.

 

Setting up port forwarding for Docker containers on CentOS 7 without using Docker Compose requires configuring firewalld correctly and running containers with the appropriate port settings. This step-by-step guide has walked you through the basic setup, which should cover most port forwarding needs for common applications. Remember that for more complex scenarios, you may need to adjust firewall or Docker settings according to the specific requirements of your application.