Accessing Private Database in VPC Locally via SSH Tunneling to Bastion
It is proper design to isolate your database from public internet access. However, what happens when you need to access it remotely? We will go over a simple approach to accessing your DB via an SSH tunnel.
Steps
Create a Bastion Instance
- Create an EC2 instance in a public subnet of the same VPC as your private database.
- Add an SSH inbound rule to your bastion’s security group that allows access from your IP address (don’t leave it open to any IP).
- Take note of the public IP (or hostname) of your instance and save the SSH key somewhere easily accessible.
Configure Access to Bastion from Development Machine
- In your computer’s
~/.ssh
folder add a folder calledkeys
and place the SSH key from your bastion there. - Reduce permission of the key by running
chmod 600 ~/.ssh/keys/the-name-of-your-key.pem
. - Add your bastion to your SSH config for easier access by adding the following code fragment to your
~/.ssh/config
file:
Host a-name-i-like-for-bastion
User ec2-user
HostName the-hostname-or-ip-of-your-bastion
IdentityFile ~/.ssh/keys/the-name-of-your-key.pem
Once you configured access to you bastion you can test by confirming that you reach it using the SSH command below:
ssh a-name-i-like-for-bastion
Access the Database
Create an SSH tunnel to the database using the command below.
ssh -L PORT_TO_MAP_ON_LOCALHOST:PRIVATE_DB_HOSTNAME_OR_IP:POST_OF_DB_ON_REMOTE a-name-i-like-for-bastion -v
Finally, you can access your database via the interface of your choice. The example below shows how to access a PostgreSQL database using psql
.
PGPASSWORD=YOUR_PASSWORD_HERE psql -h localhost -U YOUR_DB_USER_HERE -p PORT_TO_MAP_ON_LOCALHOST YOUR_DB_NAME
Hope this was helpful! If you need additional support or have software development needs contact Avantsoft.