Connecting to RDS from Laravel+Docker via bastion server(EC2)

Table of Contents

Table of Contents

RDS is configured to connect only from EC2, so if you want to connect to RDS from your local environment, you need to do some work.
In this article, I will briefly show you how to connect to RDS from a Laravel application running in a Docker container in the local environment via a bation server(EC2).

Local Environment

  • macOS:10.15.7
  • A docker container running a Laravel application.
$ docker --version
Docker version 20.10.2, build 2291f61

$ docker-compose --version
docker-compose version 1.27.4, build 40524192

Prerequisite

  • You have an bastion server(EC2) running and are ready to connect from your local environment.
  • AWS RDS is running and is ready to be connected to from the bastion server.

Overflow

  1. Create an SSH tunnel.
  2. Check the connection from the local machine (Mac) and from the Docker container.
  3. Modify the .env file so that the Laravel app can connect to the RDS.

Work

SSH tunnel

First, create an SSH tunnel.

ssh -N -L 3333:[RDS endpoint]:[RDS port] -i [pem file of bastion server] -p 22 [EC2 user]@[bastion ip]

This time, set the port number of 3333 with RDS.

Once it is created, check it with a command.

Check the connection from the local machine.

Run the following command in a terminal on your local machine to confirm.

mysql -h 127.0.0.1 -u [USER NAME] -p -D [DATABASE NAME] -P 3333

Check the connection from Docker container

Enter thr Docker container, then run the following command to check the connection.
Note that the host must be host.docker.internal.

mysql -h host.docker.internal -u [USER NAME] -p -D [DATABASE NAME] -P 3333

Modify DB settings of Laravel application

Next, modify the .env file of your Laravel application.

DB_HOST=host.docker.internal
DB_PORT=3333
DB_DATABASE=[DATABASE NAME]
DB_USERNAME=[USER NAME]
DB_PASSWORD=[PASSWAORD]

Finally, check it in the Laravel application.

Summary

  • SSH tunnel connects the local machine to the bastion server and RDS.
  • Inside the Docker container, we use host.docker.internal to interact with the local machine.