Search code examples
dockerjenkins-pipeline

How to set custom context for docker.build in jenkinsfile


I'm trying to adapt a docker build for jenkins. I'm following our docker-compose file and I'm creating a Jenkinsfile that is creating each container and linking them together. The problem I'm running into is that the docker-compose files declare a context that is not where the Dockerfile is. As far as I understand, jenkins will set the context to where the Dockerfile is, which puts files to be copied in a different relative location depending on whether the jenkinsfile or docker-compose file is building.

The folder structure is:

workspace
    |-docker
        |-db
           |-Dockerfile
           |-entrypoint.sh

This is how the Dockerfile declares the COPY instruction for the file in question

COPY docker/db/entrypoint.sh /

This is how my jenkinsfile builds the file. Which to my knowledge puts the context at that directory

docker.build("db", "${WORKSPACE}/docker/db")

the docker-compose file declares it like:

db:
build:
  context: .
  dockerfile: docker/db/Dockerfile

which puts the context at the root of the project.

Is there any way to tell a jenkinsfile to use the same context as the docker-compose file so that the Dockerfile's COPY instruction can remain unchanged and valid for both Jenkins and docker-compose? If that's not possible, does anyone know of any alternative solutions?


Solution

  • It turns out that I was pulling a previous version (1.6) of the docker-pipeline-plugin. The function in question has been since updated (1.7) to allow the second parameter to designate a Dockerfile location outside the context.

    The updated statement in my Jenkinsfile is:

    return docker.build("db", "-f docker/db/Dockerfile .")
    

    And this allows my container to build without modifying the expected context of the developer's docker-compose or Dockerfiles.