我有一个不可公开访问的 Amazon Relational Database Service (Amazon RDS) 数据库实例。我想从我的 Linux/macOS 计算机连接到该实例。如何使用堡垒主机连接到我的 RDS 数据库实例?
要连接私有 Amazon RDS 或 Amazon Aurora 数据库实例,最好使用 VPN 或 AWS Direct Connect。如果您无法使用 VPN 或 AWS Direct Connect,则首选方案是使用堡垒主机。您还可以使用此方法从 VPC 外部连接到 Aurora Serverless 和 RDS 代理。此示例说明如何设置堡垒主机以便从 Linux/macOS 计算机连接到您的 RDS 数据库实例,即使 RDS 数据库实例是私有实例也不例外。
1. 通过修改数据库实例将 Amazon RDS 数据库实例设置为私有。将可公开访问参数设置为否,使用私有子网(即路由表中没有 Internet gateway - igw)。将安全组设置为允许将数据库从所有 IP 连接到端口(5432、3306)。
2. 在与数据库实例相同的 VPC 中启动最小的可用 EC2 实例。将您的 Amazon Elastic Compute Cloud (Amazon EC2) 实例设置为可通过互联网访问并具有公有子网(即路由表中具有 Internet gateway - igw)。将安全组设置为允许使用您尝试连接的 Linux/macOS 计算机的 IP。
3. 从您的 Linux/macOS 计算机运行以下命令,创建一个隧道,以便从您的计算机进行连接:
Syntax 1: ssh -i <identity_file> -f -l <bastion-host-username> -L <local-port-you-connect-to>:<rds-endpoint>:<rds:listening-port> <bastion-host-public-ip> -v Example Command: ssh -i "private_key.pem" -f -l ec2-user -L 5432:172.31.39.62:5432 3.133.141.189 -v
在运行上述命令(SSH 隧道)时,可以配置以下设置:
Syntax 2: ssh -i "Private_key.pem" -f -N -L 5433:RDS_Instance_Endpoint:5432 ec2-user@EC2-Instance_Endpoint -v Example Command: ssh -i "private.pem" -f -N -L 5433:pg115.xxxx.us-east-2.rds.amazonaws.com:5432 ec2-user@ec2-xxxx-xxx9.us-east-2.compute.amazonaws.com -v
4.现在 SSH 隧道已经就位,您可以从本地 Linux/macOS 计算机连接到数据库实例。以下示例连接到 PostgreSQL,但您也可以使用此方法连接到 MySQL 或要连接到的任何其他引擎。
Syntax -
psql -hlocalhost -Upostgres -p -d postgres
-h = localhost
-U = the username present in the DB for connectivity
-p = 'local-port-you-connect-to' from the SSH Tunneling command
-d = Any DB, user wish to connect.
Example command -
a483e73d651f:.ssh rahul_saha$ psql -hlocalhost -Upostgres -p5432 -d postgres
Password for user postgres:
psql (12.1, server 11.5)
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off)
Type "help" for help.
postgres=> \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+----------+----------+-------------+-------------+-----------------------
postgres | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
rdsadmin | rdsadmin | UTF8 | en_US.UTF-8 | en_US.UTF-8 | rdsadmin=CTc/rdsadmin
template0 | rdsadmin | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/rdsadmin +
| | | | | rdsadmin=CTc/rdsadmin
template1 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres +
| | | | | postgres=CTc/postgres
(4 rows)
连接数据库:
$ psql -hlocalhost -Upostgres -p -d postgres $ mysql -h127.0.0.1 -uroot -p
官方文档:
https://aws.amazon.com/cn/premiumsupport/knowledge-center/rds-connect-using-bastion-host-linux/
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69946831/viewspace-3135631/ ,如需转载,请注明出处,否则将追究法律责任。