如何使用未部署在 swarm 中的 docker 容器从 docker swarm 访问服务?

Posted

技术标签:

【中文标题】如何使用未部署在 swarm 中的 docker 容器从 docker swarm 访问服务?【英文标题】:How to access a service from docker swarm using a docker container not deployed in the swarm? 【发布时间】:2017-10-27 11:50:28 【问题描述】:

我在 docker swarm 中部署了 Jenkins 和 Nexus。 Jenkins 有一个配置为通过套接字访问主机 docker 的 docker。

volumes:
  - /var/run/docker.sock:/var/run/docker.sock

此设置允许在 docker swarm 上部署的 jenkins 中使用 docker,并且运行良好。

但是,当我尝试使用 docker 容器构建 jenkins 管道并随后尝试访问 nexus 存储库时,我遇到了问题。基本上,使用 jenkins 的 swarm 部署在覆盖网络中,而 jenkins 管道使用的容器无法访问该网络。

Docker 网络如下:

docker network ls:
...
wzr8yyx6hki1        ci-cd-network   overlay             swarm
..

示例jenkins管道演示流程:

pipeline 

  agent none
  triggers  pollSCM('H/15 * * * *') 
  environment 
    NODE_IMAGE = 'node:6'
  
  stages 
    stage('Checkout') 
        agent any
          steps 
            /*generated with jenkins syntax generator*/
              checkout([$class: 'GitSCM', branches: [[name: '*/master']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[url: 'git@bitbucket.org:code/project.git']]])
                
        
    stage('Static code check (run lint)') 
            agent 
              docker  image '$NODE_IMAGE' 
            
            steps 
                sh 'npm install'
                sh 'npm run lint:ts'
      
    
    stage('Unit Test') 
            agent 
              docker  image '$NODE_IMAGE' 
            
            steps 
                sh 'npm install'
                sh 'npm publish'

            
    
  

由 jenkins 管道进程创建的容器无法访问 swarm 使用的网络“ci-cd-network”中包含 nexus 和 jenkins 机器的 nexus 服务。基本上,可以从部署在 docker swarm 中的另一个 docker 服务(“即 ping nexus”)访问 nexus 服务,但是不能从我的“节点”容器访问,该容器仅作为容器单独运行(不在 swarm 中)?知道如何使 nexus 服务对“节点”容器“可见”吗?

【问题讨论】:

【参考方案1】:

你可以将jenkins内部创建的agent容器附加到overlay网络上,容器之间就可以相互通信了。

agent 
    docker 
        image '$NODE_IMAGE'
        args  '--network ci-cd-network'
    

【讨论】:

以上是关于如何使用未部署在 swarm 中的 docker 容器从 docker swarm 访问服务?的主要内容,如果未能解决你的问题,请参考以下文章

将 Docker 容器部署到 swarm 集群中的多个节点

从零开始,使用Docker Swarm部署集群教程

Docker swarm部署

【docker swarm】docker swarm 中的网段冲突问题

docker swarm和compose 的使用(阿里)

通过docker-machine和etcd部署docker swarm集群