Docker Networking – Prevent External Access to your exposed ports

I have this problem wherein my MySQL server running in a Docker container is accessed outside the host which is a small VPS. I know because when I view the Docker logs for that MySQL container, it shows a lot of login attempts and most of the time, there are handshake errors probably caused by MySQL clients not compatible with my current MySQL version, or it could be a possible exploit. Regardless, I didn’t expect that to happen.

Attempt #1: Firewall

My first attempt to fix this is to use the ufw firewall wrapper to block external access to port 3306 (hint: I actually don’t use the default port). The firewall utility is supposed to be simple, but I can’t make it work as no matter how I set it up, it just keeps allowing remote login. The expectation is that access should only be granted on the local machine, like local Docker containers or when working on localhost like debugging or creating backups.

sudo ufw deny 3306
sudo ufw reload

Above doesn’t seem to take any effect.

Attempt #2: Move to AWS EC2 and setup infra-level security policies

I just thought about moving to AWS EC2 and use their beautiful security groups and security policies, but it is just a thought. I don’t want to move servers and it may cost may a little bit more for lower specs. So no.

Simple Fix: Docker networking

After some research, I stumbled upon a post wherein you can actually map the exposed Docker container port to a specific hostname or IP address.

From:

# docker-compose.yml
version: '3.2'
services:
  db:
    image: mysql:5.7
    ports:
      - "3306:3306"

To:

version: '3.2'
services:
  db:
    image: mysql:5.7
    ports:
      - "127.0.0.1:3306:3306"

See? So easy! When I tried to access my MySQL server remotely, I’m now denied and the error says that the port is not allowed or something. That’s it!

This entry was posted in Database, Docker, MySQL. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *