无法链接到由 docker-compose 启动的正在运行的容器 [英] Cannot link to a running container started by docker-compose

查看:50
本文介绍了无法链接到由 docker-compose 启动的正在运行的容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 docker 容器设置我的本地开发环境.docker-compose.yml 如下所示

I am setting up my local development environment with docker containers. The docker-compose.yml is like following

version: '2'

services:
  db:
    image: mongo:3
  mq:
    image: rabbitmq:3
  api:
    build: .
    image: my_app/api
    ports:
      - "3000:3000"
    links:
      - db
      - mq
    environment:
      - NODE_ENV=development

它开始没有错误.并且 docker 列出了 3 个正在运行的容器

It starts without error. And docker lists 3 running containers

docker-compose up -d
docker ps

e90e5a8b5d33        my_app/api    "/usr/local/bin/node "   0.0.0.0:3000->3000/tcp               my_app_api_1
42bfcd971b16        mongo:3       "/entrypoint.sh mongo"   27017/tcp                            my_app_db_1
a0685a816c47        rabbitmq:3    "/docker-entrypoint.s"   4369/tcp, 5671-5672/tcp, 25672/tcp   my_app_mq_1

但是,当我尝试从另一个容器链接到那些正在运行的容器时

However when I try to link to those running containers from another container

docker run --link my_app_mq_1:mq --link my_app_db_1:db -it worker 

出现错误

 docker: Error response from daemon: Cannot link to /my_app_mq_1, as it does not belong to the default network.

我也试过

 docker run --link my_app_mq_1:mq --link my_app_db_1:db -it --net default worker 

同样的错误.

那么如何链接到由 docker-compose 启动的正在运行的容器?

So how can I link to a running container started by docker-compose?

推荐答案

好的,找到答案了.如果其他人遇到同样的问题,请执行

Ok, found the answer to it. In case anyone else comes across the same problem, just do

docker network ls

此命令列出所有 docker 网络.当您运行 docker-compose up 时,docker-compose 将创建一个新网络.在我的例子中,网络被命名为 myapp_default.

This command lists all the docker networks. docker-compose will create a new network when you run docker-compose up. In my case, the network is named as myapp_default.

注意:您的应用程序网络的名称基于项目名称",该名称基于其所在目录的名称.您可以使用 --project-name 标志或COMPOSE_PROJECT_NAME 环境变量.Compose 中的网络

Note: Your app’s network is given a name based on the "project name", which is based on the name of the directory it lives in. You can override the project name with either the --project-name flag or the COMPOSE_PROJECT_NAME environment variable. Networking in Compose

所以链接到这些容器的正确方法是

So the correct way to link to those containers is

docker run --link my_app_mq_1:mq --link my_app_db_1:db -it --net myapp_default worker 

这篇关于无法链接到由 docker-compose 启动的正在运行的容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆