Recently at @pushe I used gitlab-ci and docker to deploy some of our services. While using docker in our production environment we wanted to know which build is currently running there.

Gitlab-CI provides a nice environment variable named $CI_PIPELINE_ID which contains a build id for current pipline and I wanted to somehow inject this variable into images default environment variables.

I already knew how to set an environment variable while building image:

# from Dockerfile
ENV NAME VALUE

And I found out that there is an argument named --build-arg for docker build to send a variable within container, which can be used with ARG command

so here is what i’ve done:

I changed our build command to this:

# old command
docker build -t tag_name .
# new command
docker build --build-arg CI_PIPELINE_ID=$CI_PIPELINE_ID -t tag_name .

then added these lines to our Dockerfile

# Dockerfile
ARG CI_PIPELINE_ID
ENV BUILD_VERSION ${CI_PIPELINE_ID}

Tada! now whenever I run the container BUILD_VERSION is set to CI_PIPELINE_ID.