Home > Net >  Jenkins docker container: run docker build inside the container
Jenkins docker container: run docker build inside the container

Time:05-02

I have a VM with Linux CentOS 7, and inside this VM, there is an active Docker daemon, running a container of a Jenkins instance (LTS). This instance is responsible of running a pipeline described in a Jenkinsfile, in which the last stage is the docker build of a Dockerfile. I attach to this post a photo of my current architecture to be as clear as possible.

My actual architecture: a VM with Linux CentOS 7, and inside this VM, there is an active Docker daemon, running a container of a Jenkins instance (LTS).

My task is: successfully execute all the pipeline's stage, in particular the last one, the build of che Dockerfile.

But, I ran into a problem: inside the container I can't launch the docker daemon, so, how can I launch the build of the Dockerfile, if I am inside a container?

A colleague suggested me to configure a Jenkins Agent on the VM, outside of the docker daemon, but is it possible? If yes, how?

Or maybe it's better to opt for other solutions?

Thanks in advance!

CodePudding user response:

First of all, you can build docker image within the Jenkins container and if you're using declarative Jenkinsfile, then install docker pipeline plugin. See how to exploit and docs in the following links.

https://plugins.jenkins.io/docker-workflow/

https://docs.cloudbees.com/docs/admin-resources/latest/plugins/docker-workflow

In order to build your Dockerfile, see the code snippet below

stage("Build") {
        steps {
            script {
                myImage = docker.build("team/my-image:latest") // build the Dockerfile
            }
        }
    }

    // you can execute your Docker container and run some specific command you desire
    stage("Run Docker Container") {
        steps {
            script {
                sh "docker network create --driver bridge prod_bridge || true"
                myImage.withRun("--network-alias prod_bridge_alias --net prod_bridge --name my-container") {c ->
                    sh """
                        docker logs my-container
                    """
                }
            }
            sh "docker network rm prod_bridge"
            sh "docker rmi team/my-image:latest"
        }
    }

However, somewhat you might be faced some issues such as out of resources ( space/ cpu/ memory), or any other technical issues related to "docker in docker", which is not recommended, which are explained in Jerome's post.

Also see the question on Stackoverflow Is it ok to run docker from inside docker?

You can consider installing Jenkins and all required plugin in the Jenkins instance on your VM, as your colleague recommended.

It's up to you!

  • Related