Sai
Sai

Reputation: 2032

Get docker container ID and it's host path from within the container

I'm running a Jenkins declarative pipeline in which a stage runs on a docker container and outputs a file. I would like to copy this file from the container onto the host's git init path, so that I can commit the newly outputted file to the source git repository.

In-order to copy the outputted file from container to host's git init path, I can use the docker cp command for which I need the container ID and the destination path which in this case is the host's git init path.

Can someone share thoughts on how to get these 2 values?

Upvotes: 0

Views: 2487

Answers (2)

Devin_92
Devin_92

Reputation: 11

you can get docker container ID inside the container by this cmd:

cat /proc/self/cgroup | grep -o  -e "docker-.*.scope" | head -n 1 | sed "s/docker-\(.*\).scope/\\1/"

Upvotes: 1

David Maze
David Maze

Reputation: 158848

Generally you don't do either of these things. Docker is an isolation system that's intended to hide most of the details of the host system from the container (and vice versa); also the container filesystem tends to not be stored on the host in a way that's easy to extract.

When you're Using Docker with Pipeline, it knows how to mount the current working tree into containers, so the easiest way to do this is something like

stage('Something') {
  agent {
    docker { image 'my-image' }
  }
  steps {
    sh 'the_command'
  }
}

or, if you're using scripted pipelines

docker.image('my-image').inside {
  sh 'the_command'
}

In both of these cases the_command will run with its current working directory being the per-build workspace directory; it doesn't need to know that it's running inside Docker or to know anything about the host, and any changes it writes into this directory will be visible elsewhere in your build.

More broadly, if you want a process inside a container to produce files that are visible on the host, you need to use a docker run -v option to mount a host directory into the container at the time you run it. (In the previous examples, the Jenkins logs will include a detailed docker run command that shows these options.) If the primary goal of your application is to produce host-visible files, running it outside Docker might be easier. If Jenkins is running inside Docker too, note that the first path option to docker run -v is always a path on the physical host, and there's no way to map one container's filesystem into another.

Upvotes: 1

Related Questions