×


How to Allow Docker Ports with iptables ?

Docker is a popular containerization platform that allows you to create and run isolated applications. By default, Docker containers are not accessible from outside the host machine. This is done to protect your system from security risks.


However, there may be times when you need to allow access to a Docker container from outside your network. For example, you might want to expose a web server or database to the internet. In these cases, you can use iptables to allow incoming and outgoing traffic on specific ports used by Docker containers.


Here at IbmiMedia, we shall look into how to use iptables to allow Docker ports. 



What is iptables?

iptables is a Linux firewall that allows you to control network traffic. It is used to manage a variety of firewall rules, including those that allow or deny access to specific ports.



How to Allow Docker Ports with iptables ?

To allow Docker ports with iptables, you will need to create a new rule in the DOCKER chain. The DOCKER chain is used by Docker to manage its own firewall rules.

The following command will allow incoming traffic on port 8080 for any Docker container:

iptables -I DOCKER -p tcp --dport 8080 -j ACCEPT

This rule will allow any incoming TCP connections on port 8080 to any Docker container.


You can also allow outgoing traffic on a specific port by using the -o option. For example, the following command will allow outgoing traffic on port 22 for any Docker container:

iptables -I DOCKER -o eth0 -p tcp --dport 22 -j ACCEPT

This rule will allow any outgoing TCP connections on port 22 to any Docker container, but only on the eth0 interface.


How to Save and Reload iptables Rules ?

Once you have created your iptables rules, you need to save them and reload the firewall. To do this, run the following commands:

iptables-save
service iptables restart

The iptables-save command will save your rules to a file. The service iptables restart command will reload the firewall with your new rules.


Conclusion

By following the steps in this guide, you can easily allow Docker ports with iptables. This will allow you to access your Docker containers from outside your network, while still maintaining a secure environment.


For more information on iptables, please refer to the iptables documentation: https://linux.die.net/man/8/iptables.