# Firewall to allow certain ports/IPs or combination fo both:
Note: At first, you need to install the Firewall package: '
firewalld'. For Ubuntu users to get it installed on your web server, use this command:
sudo apt install firewalld --yes
1.1) Allow a certain port
Code:
sudo firewall-cmd --zone=docker --add-port=80/tcp
sudo firewall-cmd --zone=docker --permanent --add-port=80/tcp
PS: in the above example, we are setting a rule for the webserver to allow any incoming HTTP traffic on port 80. You can replace 80 with any other port (such as 443 for HTTPS) as per your needs. These ports could be of type tcp and/or udp
1.2) allow a certain IPv4 address
Code:
sudo firewall-cmd --zone=public --add-source=172.217.22.14/32
sudo firewall-cmd --zone=public --permanent --add-source=172.217.22.14/32
Use case: suppose you are hosting your website on Wordpress. And you might have good traffic, so for the best performance, you have a separate VPS, which will only be responsible for handling your site database (i.e., MySQL). But you want to restrict database server access from your wordpress web server only (basically where Apache/Nginx is running). So in that case, you can use this approach to whitelist only your Apache/Nginx Server IP on your MySQL Server.
So in this case, you need to run these firewall commands on your server, where your database (MySQL) is holding, and the IP address will be the one where your Apache/Nginx server is running.
Note: You can replace the given IP with any other IP address. And the /32 subnet mask basically says that it is applicable for that single IP only.
1.3) allow a certain Port from a specific IPv4 address only
Code:
sudo firewall-cmd --zone=public --add-rich-rule='rule family="ipv4" source address="172.217.22.14/32" port protocol="tcp" port="3306" accept'
sudo firewall-cmd --permanent --zone=public --add-rich-rule='rule family="ipv4" source address="172.217.22.14/32" port protocol="tcp" port="5432" accept'
Use case: similar to the 1.2 use case, but it gives you a more granular level of control. So the above two commands allow your web server (Apache/nginx) to access only port 3306 (where MySQL is running) and not any other ports of your MySQL server.
Remember: these two commands need to be run on your MySQL server, and the IP address will be the one where your web server (Apache/Nginx) is running. So basically, your MySQL server is allowing your web server IP to access the database, which is running on port 3306.