如何通过SSH端口转发访问AWS MySQL,实现Django与Jupyter本地开发
Got it, let's sort out this annoying workflow so you can focus on prototyping instead of fumbling with SSH commands every time. Here's a step-by-step guide tailored exactly to your setup:
Step 1: Set Up a Temporary SSH Tunnel
First, we'll create a tunnel that routes your local machine's traffic through server Y to reach the MySQL instance on X. Open your terminal and run this command:
ssh -L 3307:ec2-xxx-xxx-xxx-xx.compute-1.amazonaws.com:3306 ec2-yy-yyy-yyy-yy.compute-1.amazonaws.com
3307: This is a local port we're using (pick any unused port if 3307 is taken)ec2-xxx-xxx-xxx-xx.compute-1.amazonaws.com:3306: The target MySQL instance and portec2-yy-yyy-yyy-yy.compute-1.amazonaws.com: Your jump server Y
If you want the tunnel to run in the background (so you can keep using your terminal), add -fN:
ssh -fN -L 3307:ec2-xxx-xxx-xxx-xx.compute-1.amazonaws.com:3306 ec2-yy-yyy-yyy-yy.compute-1.amazonaws.com
Step 2: Connect to MySQL Locally
Now you can use your local MySQL client or development tools (like DBeaver, PyCharm, or even the mysql CLI) as if you're connecting directly to X. Use these details:
- Host:
localhost - Port:
3307 - Username/Password: The same credentials you use to access the MySQL instance on X
For example, with the CLI:
mysql -h localhost -P 3307 -u your-mysql-username -p
Step 3: Simplify with SSH Config (No More Long Commands)
To avoid typing that full tunnel command every time, add a shortcut to your SSH config file:
- Open
~/.ssh/config(create it if it doesn't exist) - Add this block:
Host mysql-jump HostName ec2-yy-yyy-yyy-yy.compute-1.amazonaws.com LocalForward 3307 ec2-xxx-xxx-xxx-xx.compute-1.amazonaws.com:3306 User your-ssh-username-on-Y # Replace with your actual username on server Y
- Save the file, then start the tunnel with just:
ssh mysql-jump # Or for background mode: ssh -fN mysql-jump
Step 4: Keep the Tunnel Alive (For Long Sessions)
If your tunnel keeps dropping during prototyping, use autossh to automatically reconnect it. Install autossh first (via brew install autossh on Mac, sudo apt install autossh on Ubuntu/Debian), then run:
autossh -M 0 -fN -L 3307:ec2-xxx-xxx-xxx-xx.compute-1.amazonaws.com:3306 ec2-yy-yyy-yyy-yy.compute-1.amazonaws.com
-M 0disables the monitoring port (cleaner setup)- The tunnel will now restart automatically if it disconnects
Quick Notes to Avoid Snags
- If port 3307 is already in use on your local machine, just swap it for another unused port (like 3308) in all the commands above
- Double-check that server Y's security group allows outbound traffic to X's 3306 port, and X's security group allows inbound traffic from Y's IP
- Make sure your local firewall isn't blocking the port you're using for the tunnel
Once this is set up, you can run scripts, test prototypes, and use your favorite tools locally without the SSH hop hassle. Let me know if you run into any issues getting this working!
内容的提问来源于stack exchange,提问作者Deepak

