How to instruct Jenkins to use the dind container as docker_host?

41 Views Asked by At

I am absolutely new to Jenkins and I am having an hard time figuring out how to instruct Jenkins Docker pipeline to use the dind container as docker_host.

Below is my jenkins docker-compose yaml file:

version: '3.9'

networks:
  jenkins:

volumes:
  data:
  certs:

services:
  dind:
    image: docker:dind
    privileged: true    # Necessary for running Docker inside Docker
    restart: unless-stopped
    networks:
      jenkins:
        aliases:
          - docker
    volumes:
      - data:/var/jenkins_home
      - certs:/certs/client
    environment:
      - DOCKER_TLS_CERTDIR=/certs
    ports: 
      - 2376:2376

  jenkins:
    image: jenkins/jenkins:lts-jdk17
    container_name: jenkins
    restart: unless-stopped
    links:
      - dind
    networks: 
      jenkins:
        aliases: 
          - docker
    volumes:
      - data:/var/jenkins_home
      - certs:/certs/client:ro
    environment:
      - DOCKER_TLS_VERIFY=1
      - DOCKER_HOST=tcp://docker:2376
      - DOCKER_TLS_CERT_PATH=/certs/client
    ports:
      - 8080:8080
      - 50000:50000

This is a pipeline example I tried (mostly put together with the help of Google and ChatGPT :| )

pipeline {
    agent {
        docker {
            image 'golang:1.17-alpine'  // Use a Go image to install Go
        }
    }
    environment {
        GOPATH = '/go'
        PATH = "${GOPATH}/bin:${PATH}"
    }
    stages {
        stage('Install Go') {
            steps {
                sh 'go version'  // Verify Go installation
            }
        }
        stage('Build Docker Image') {
            steps {
                script {
                    // Build Docker image using Docker CLI commands
                    docker.build("my-golang-app:${BUILD_NUMBER}")
                }
            }
        }
    }
    options {
        environment {
            DOCKER_HOST = 'tcp://docker:2376'  // Specify DinD container host and port
        }
    }
    post {
        always {
            cleanWs()
        }
    }
}

The result is an issue with the code about the environment instruction I just can't seem to resolve. To be honest I am not even sure this the right approach.

Thank you.

0

There are 0 best solutions below