无法从 EC2 中的 docker 容器 运行 连接到 elasticache redis

Can't connect to elasticache redis from docker container running in EC2

作为我的 CI 过程的一部分,我正在创建一个 docker-machine EC2 实例,并通过 docker-撰写。服务器容器测试脚本尝试连接到与 EC2 相同的 VPC 中的 AWS elasticache redis 实例。当测试脚本为 运行 时,出现以下错误:

1) Storage
       check cache connection
         should return seeded value in redis:
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/usr/src/app/test/scripts/test.js)
      at listOnTimeout (internal/timers.js:549:17)
      at processTimers (internal/timers.js:492:7)

更新:我可以通过 EC2 本身的 redis-cli 连接:

redis-cli -c -h ***.cache.amazonaws.com -p 6379 ping
> PONG

看起来我无法连接到我的 redis 实例,因为我的 docker 容器使用的 IP 与我的 elasticache 实例不在同一个 VPC 中。在从远程图像构建容器时,如何设置我的 docker 配置以使用与主机相同的 IP?任何帮助将不胜感激。

我的相关部分 docker-compose.yml:

version: '3.8'
services:
  server:
    build:
      context: ./
      dockerfile: Dockerfile
    image: docker.pkg.github.com/$GITHUB_REPOSITORY/$REPOSITORY_NAME-server:github_ci_$GITHUB_RUN_NUMBER
    container_name: $REPOSITORY_NAME-server
    command: npm run dev
    ports:
      - "8080:8080"
      - "6379:6379"
    env_file: ./.env

服务器容器 Dockerfile:

FROM node:12-alpine

# create app dir
WORKDIR /usr/src/app

# install dependencies
COPY package*.json ./

RUN npm install

# bundle app source
COPY . .

EXPOSE 8080 6379

CMD ["npm", "run", "dev"]

Elasticache redis SG入站规则:

EC2 SG 入站规则:

我通过反复试验解决了这个问题。在 Docker 文档中找到了为我指明正确方向的主要提示:

By default, the container is assigned an IP address for every Docker network it connects to. The IP address is assigned from the pool assigned to the network...

Elasticache 实例只能从其各自的 VPC 内部访问。根据我的配置,docker 容器和 ec2 实例 运行 在 2 个不同的 IP 地址上,但只有 EC2 IP 被列入白名单以连接到 Elasticache。

我必须通过将容器 network_mode 设置为 "host":

将 docker 容器 IP 绑定到我 docker.compose.yml 中的主机 EC2 IP
version: '3.8'
services:
  server:
    image: docker.pkg.github.com/$GITHUB_REPOSITORY/$REPOSITORY_NAME-server:github_ci_$GITHUB_RUN_NUMBER
    container_name: $REPOSITORY_NAME-server
    command: npm run dev
    ports:
      - "8080:8080"
      - "6379:6379"
    network_mode: "host"
    env_file: ./.env
...