Docker中SSH隧道容器无法被其他容器访问远程MySQL的问题
Let’s cut straight to the issue: your SSH tunnel is only listening on the loopback address (127.0.0.1) inside the ssh_mysql container. That means other containers on your Docker network can’t reach the tunnel port—they’re trying to connect to the container’s network-facing IP, but the port isn’t open there. Here’s how to fix it step by step:
1. Update Your SSH Tunnel Command
Modify your SSH command to bind the tunnel port to 0.0.0.0 instead of the default 127.0.0.1. This makes the port listen on all network interfaces of the container, including the Docker network interface:
ssh user@example.com -4 -L 0.0.0.0:33306:127.0.0.1:3306 -N
-L 0.0.0.0:33306:127.0.0.1:3306: Tells SSH to forward any traffic arriving on any IP of the container at port 33306 to the remote server’s 127.0.0.1:3306.-N: Keeps SSH running without executing a remote command (ideal for tunnels).
2. Ensure Your ssh_mysql Container is Set Up Correctly
Make sure your Dockerfile for the ssh_mysql container installs OpenSSH client and runs the corrected tunnel command. Here’s a minimal example:
# Use a lightweight base image FROM alpine:latest # Install OpenSSH client RUN apk add --no-cache openssh-client # Optional: Disable strict host key checking to avoid interactive prompts RUN echo "StrictHostKeyChecking no" >> /etc/ssh/ssh_config # Run the SSH tunnel command CMD ["sh", "-c", "ssh user@example.com -4 -L 0.0.0.0:33306:127.0.0.1:3306 -N"]
Critical Pre-Requisite:
Ensure the container can authenticate to the remote server without a password:
- Mount your private key (
id_rsa) into/root/.ssh(your docker-compose already does this) - Add the corresponding public key to the remote server’s
~user/.ssh/authorized_keysfile.
3. Verify Port Listening in the Tunnel Container
After starting the containers, exec into the ssh_mysql container to confirm the port is listening on 0.0.0.0:
docker-compose exec ssh_mysql netstat -tulpn
You should see a line like this:
tcp 0 0 0.0.0.0:33306 0.0.0.0:* LISTEN 1/ssh
If it shows 127.0.0.1:33306, double-check your SSH command—you didn’t bind to 0.0.0.0 correctly.
4. Test the Connection from the PHP Container
Now try connecting again from your PHP container:
docker-compose exec php mysql -h ssh_mysql -P 33306 -u user -p
This should work now that the tunnel port is accessible across the Docker network.
Bonus: Improve Tunnel Reliability
For production or long-running setups, use autossh instead of plain SSH to automatically re-establish the tunnel if it drops. Install it in your ssh_mysql container:
RUN apk add --no-cache autossh
Then update the CMD to:
autossh -M 0 -o "StrictHostKeyChecking no" -4 -L 0.0.0.0:33306:127.0.0.1:3306 user@example.com -N
-M 0: Disables monitoring port (we don’t need it for basic reconnection)
内容的提问来源于stack exchange,提问作者martes

