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


  • A bastion server(EC2) which can be accessed from your local environment.
  • An AWS RDS which can be accessed from the bastion server.


  1. Create a 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.

SSH tunnel

First, create a 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 -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.


Finally, check it in your Laravel application.


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