Usama
Usama

Reputation: 480

can not ssh to another Docker Container docker-compose

I have a docker image which i am using as my git server, i have all my data in it. then i have a database container where i need to clone data from my git docker server.

my docker-compose.yml file is:

version: '3'

services:
  git-server:
    image: git:latest
    build:
      context: git
    ports:
      - "22:22"

  my-db:
    image: my-db:latest
    build:
      context: db
    ports:
      - "5433:5432"
    links:
      - git-server

for git docker i am only creating git repos only.

FROM kinogmt/centos-ssh:latest

......

RUN mkdir /home/git/dashboard.git
WORKDIR /home/git/dashboard.git
RUN git --bare init && git --bare fetch [email protected]:****/******.git
.......
EXPOSE 22

and in my database dockerfile i am cloning that repo.

From centos:centos7

.......
RUN git clone git@git-server:dashboard.git
.......

when i run docker-compose build

it says

ssh: Could not resolve hostname git-server: Name or service not known fatal: Could not read from remote repository.

Please make sure you have the correct access rights and the repository exists.

Upvotes: 1

Views: 832

Answers (1)

BMitch
BMitch

Reputation: 264831

At build time, containers are not attached to the bridge network (nor are they connected to volumes). If you need container to container networking, you need to move that workflow into your entrypoint or command you run when the container starts.


Commands executed with a RUN in the Dockerfile are performed at build time. When docker is building your image, it does so without networking to other containers, without volumes mounted, and without any dependencies on other containers. It simply takes the previous state from the prior line, creates a temporary container that runs that RUN command, and captures the resulting layers. So attempts to use container-to-container networking will fail because the other containers do not exist at build time. Builds should be reproducible and independent from external artifacts when possible, so this needs a redesign.

As a redesign, I'd personally remove the git clone from your image steps and include the code in the repo where your Dockerfile lives. Do any checkouts before starting the build. This has the advantage of keeping any secrets to log into a private repo out of your image. Then inside your build, you would just do a COPY of the files into your image instead of a git fetch.

The other option if there's a need for container-to-container communication for your process is to run a script in your CMD or ENTRYPOINT that runs any steps you need when the container is run vs when the image is built.

Upvotes: 2

Related Questions