微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法从EC2中运行的Docker容器连接到Elasticache Redis

如何解决无法从EC2中运行的Docker容器连接到Elasticache Redis

作为我CI流程的一部分,我正在创建一个docker-machine EC2实例,并通过docker-compose在其中运行2个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)

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

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入站规则:

enter image description here

EC2 SG入站规则:

enter image description here

解决方法

我通过广泛的反复试验解决了这个问题。在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实例在两个不同的IP地址上运行,但是只有EC2 IP被列入白名单以连接到Elasticache。

我必须通过将容器docker.compose.yml设置为network_mode将docker容器IP绑定到"host"中的主机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
...

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。