DEV Community

brunt@jp
brunt@jp

Posted on • Edited on • Originally published at cyublog.com

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

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 bastion server(EC2).

Original Post

cyublog | Connecting to RDS from Laravel+Docker via bastion 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
Enter fullscreen mode Exit fullscreen mode

Pre-conditions

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

Workflow

  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]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

Finally, check it in your Laravel application.

Top comments (0)