A simple guide to UFW (Uncomplicated Firewall) in Linux
When you start your self-hosting journey, one of the first issues you are going to run into is that your docker app might fail to load on the first try.
Turns out, this is actually a good thing - it means that your firewall is up and protecting your server from unauthorized access.
Most Linux distributions come with UFW pre-installed, but in case it's missing, you can install it with:
sudo apt install ufw
Once installed, check its status:
sudo ufw status
If it's inactive, enable it with:
sudo ufw enable
The ufw utility in Linux works on a deny-by-default basis. This means once it's enabled, all incoming traffic is blocked unless explicitly allowed. So we will have to enable the ports ourselves for our apps to work. Here are some common commands that would come in handy:
1. Allowing SSH Traffic
When self-hosting, remote management via SSH is common. To allow SSH access:
sudo ufw allow ssh
This command opens port 22, which is the default SSH port. If you're using a custom port, specify it like this:
sudo ufw allow 2222/tcp
2. Opening Web Server Ports (HTTP/HTTPS)
If you're hosting a website using Ghost CMS or any other application, you'll need to open ports 80 (HTTP) and 443 (HTTPS):
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
This will allow traffic to your web server.
3. Limiting Access to Services
For security, you may want to restrict access to specific services based on IP. For example, if you’re running a database service that should only be accessible locally or from a specific IP:
sudo ufw allow from 192.168.1.10 to any port 5432
This only allows the IP 192.168.1.10
to access your PostgreSQL database.
4. Allowing Specific Ports for Docker Containers
If you're hosting applications through Docker, you may need to allow access to custom ports. For instance, if you have an app running on port 8080 inside a Docker container:
sudo ufw allow 8080/tcp
5. Blocking All Incoming Traffic Except for Specific Ports
To ensure your server remains locked down except for essential services, run:
sudo ufw default deny incoming
sudo ufw allow ssh
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
This configuration will block all incoming traffic except for SSH and web traffic.
That's pretty much all you need to know to start tinkering around your firewall in Linux.