Skip to content

Jenkins Docker Connection Pipeline

Docker Pipeline Requirements:

  • Jenkins must have access to the Docker daemon on the host.

  • If Jenkins runs inside a container:

    • Mount the Docker socket: /var/run/docker.sock:/var/run/docker.sock
    • Mount the Docker binary if needed: /usr/bin/docker:/usr/bin/docker
    • Run Jenkins as root inside the container or ensure the Jenkins user belongs to the docker group.
  • This allows commands like docker pull, docker run, and docker exec from your Jenkins pipeline to work correctly.

groovy
pipeline {
    agent any
    environment {
        IMAGE_NAME = "nginx:alpine"
        CONTAINER_NAME = "nginx-test-container"
        HOST_PORT = "8084"
    }
    stages {
        stage('Pull Nginx Image') {
            steps {
                script {
                    sh "docker pull ${IMAGE_NAME}"
                }
            }
        }

        stage('Run Nginx Container') {
            steps {
                script {
                    // Remove any existing container with the same name
                    sh "docker rm -f ${CONTAINER_NAME} || true"

                    // Run container in detached mode
                    sh "docker run -d --name ${CONTAINER_NAME} -p ${HOST_PORT}:80 ${IMAGE_NAME}"
                }
            }
        }

        stage('Test Container') {
            steps {
                script {
                    // Run a test command inside the container
                    sh "docker exec ${CONTAINER_NAME} ls -la /usr/share/nginx/html"
                }
            }
        }

        stage('Clean Up') {
            steps {
                script {
                    sh "docker stop ${CONTAINER_NAME} || true"
                    sh "docker rm ${CONTAINER_NAME} || true"
                }
            }
        }
    }
}