How to Set Up a Secure SSH Tunnel for MySQL Access with a Restricted User

Introduction

In many scenarios, database servers are not exposed directly to the internet for security reasons. However, developers and applications still need to connect to them securely. One of the best solutions is to create an SSH tunnel that forwards local connections to the remote MySQL server.

In this guide, we will:

  • Create a restricted SSH user who can only tunnel and not log in interactively.
  • Use /sbin/nologin to prevent shell access.
  • Set up port forwarding for secure MySQL access.
  • Test and verify the tunnel.

Step 1: Create the SSH User

On the SSH gateway server, create a dedicated user:

Set a strong password when prompted.

Step 2: Restrict the User to SSH Tunneling Only

Set the User’s Shell to /sbin/nologin

To prevent interactive logins, change the user’s shell:

Restrict the User in SSH Configuration

Edit the SSH config file:

Add the following at the bottom:

Restart SSH:

Step 3: Set Up the SSH Tunnel

On your local machine, use the following SSH command to set up a tunnel:

Step 4: Verify the Tunnel

Once the SSH command is running, connect to MySQL via the tunnel:

Optional: Use SSH Key Authentication Instead of Passwords

Step 1: Generate SSH Key on Your Local Machine

Step 2: Copy the Key to the Server

Optional: Automatically Start the Tunnel on Boot

To make the SSH tunnel start automatically on reboot, create a systemd service:

Add:

Enable it:

Conclusion

By following this guide, you have successfully created a secure, restricted SSH tunnel to access a remote MySQL database without exposing it to the public internet. Here’s what we achieved:

Created a restricted SSH user (mysqltunnel)
Disabled interactive shell access (/sbin/nologin)
Configured SSH to allow only tunneling
Set up an SSH tunnel to MySQL securely
Verified the connection with MySQL Workbench
Optionally enabled SSH key authentication
Configured automatic tunnel startup on boot

Would you like to add firewall rules or further harden the security of this setup? Let us know in the comments! 

Have a project or a problem?

Talk with a senior engineer for practical recommendations—no obligation.

Leave a comment

Leave a Reply

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

Related Posts

Categories

Get a free consultation from Reliable Penguin

Submit the form—or for immediate service call 866-649-7984.