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.
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
~/.sshfolder add a folder called
keysand 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
Once you configured access to you bastion you can test by confirming that you reach it using the SSH command below:
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
PGPASSWORD=YOUR_PASSWORD_HERE psql -h localhost -U YOUR_DB_USER_HERE -p PORT_TO_MAP_ON_LOCALHOST YOUR_DB_NAME