docker - Jenkins Golang 声明性管道 : Build Docker Image and Push to Docker Hub

标签 docker go jenkins jenkins-pipeline

我正在尝试为我的 Golang 项目创建一个 Docker 镜像,并通过 Jenkins 声明式管道将其上传到 Docker Hub。

我能够构建我的项目并运行我的所有测试。

我的Jenkinsfile如下:

#!/usr/bin/env groovy
// The above line is used to trigger correct syntax highlighting.

pipeline {
    agent { docker { image 'golang' } }

    stages {
        stage('Build') {   
            steps {                                           
                // Create our project directory.
                sh 'cd ${GOPATH}/src'
                sh 'mkdir -p ${GOPATH}/src/MY_PROJECT_DIRECTORY'

                // Copy all files in our Jenkins workspace to our project directory.                
                sh 'cp -r ${WORKSPACE}/* ${GOPATH}/src/MY_PROJECT_DIRECTORY'

                // Copy all files in our "vendor" folder to our "src" folder.
                sh 'cp -r ${WORKSPACE}/vendor/* ${GOPATH}/src'

                // Build the app.
                sh 'go build'
            }            
        }

        // Each "sh" line (shell command) is a step,
        // so if anything fails, the pipeline stops.
        stage('Test') {
            steps {                                
                // Remove cached test results.
                sh 'go clean -cache'

                // Run Unit Tests.
                sh 'go test ./... -v'                                  
            }
        }           
    }
}   

我的Dockerfile(如果需要)如下:

# Make a golang container from the "golang alpine" docker image from Docker Hub.
FROM golang:1.11.2-alpine3.8

# Expose our desired port.
EXPOSE 9000

# Create the proper directory.
RUN mkdir -p $GOPATH/src/MY_PROJECT_DIRECTORY

# Copy app to the proper directory for building.
ADD . $GOPATH/src/MY_PROJECT_DIRECTORY

# Set the work directory.
WORKDIR $GOPATH/src/MY_PROJECT_DIRECTORY

# Run CMD commands.
RUN go get -d -v ./...
RUN go install -v ./...

# Provide defaults when running the container.
# These will be executed after the entrypoint.
# For example, if you ran docker run <image>,
# then the commands and parameters specified by CMD would be executed.
CMD ["MY_PROJECT"]

我可以通过以下方式获取我的 Docker Hub 凭据:

environment {
    // Extract the username and password of our credentials into "DOCKER_CREDENTIALS_USR" and "DOCKER_CREDENTIALS_PSW".
    // (NOTE 1: DOCKER_CREDENTIALS will be set to "your_username:your_password".)
    // The new variables will always be YOUR_VARIABLE_NAME + _USR and _PSW.
    DOCKER_CREDENTIALS = credentials('MY_JENKINS_CREDENTIAL_ID')
}

作为引用,以下是我在 Freestyle 工作中的工作内容:

Execute Shell:

    # Log in to Docker.
    sudo docker login -u $DOCKER_USERNAME -p $DOCKER_PASSWORD

    # Make a Docker image for our app.
    cd /var/lib/jenkins/tools/org.jenkinsci.plugins.golang.GolangInstallation/Go/src/MY_PROJECT_DIRECTORY/
    sudo docker build -t MY-PROJECT-img .

    # Tag our Docker image.
    sudo docker tag  MY-PROJECT-img   $DOCKER_USERNAME/MY-PROJECT-img

    # Push our Docker image to Docker Hub.
    sudo docker push $DOCKER_USERNAME/MY-PROJECT-img

    # Log out of Docker.
    docker logout

注意:我通过执行以下操作授予 Jenkins sudo 权限:

  1. 打开 sudoers 文件进行编辑:

    sudo visudo -f/etc/sudoers

  2. 按“i”进入插入模式。

  3. 粘贴以下内容:

    Jenkins ALL=(ALL) NOPASSWD: ALL

  4. 按“ESC”退出插入模式。

  5. 要保存,请输入:

    :w

  6. 要退出,请输入:

    :q

我相信这应该可以通过在我的声明式管道中添加一个新的 stageagent 来实现,但我在网上找不到任何东西。

最佳答案

我想通了。

我更新后的Jenkinsfile如下:

#!/usr/bin/env groovy
// The above line is used to trigger correct syntax highlighting.

pipeline {
    // Lets Jenkins use Docker for us later.
    agent any    

    // If anything fails, the whole Pipeline stops.
    stages {
        stage('Build & Test') {   
            // Use golang.
            agent { docker { image 'golang' } }

            steps {                                           
                // Create our project directory.
                sh 'cd ${GOPATH}/src'
                sh 'mkdir -p ${GOPATH}/src/MY_PROJECT_DIRECTORY'

                // Copy all files in our Jenkins workspace to our project directory.                
                sh 'cp -r ${WORKSPACE}/* ${GOPATH}/src/MY_PROJECT_DIRECTORY'

                // Copy all files in our "vendor" folder to our "src" folder.
                sh 'cp -r ${WORKSPACE}/vendor/* ${GOPATH}/src'

                // Build the app.
                sh 'go build'               
            }            
        }

        stage('Test') {
            // Use golang.
            agent { docker { image 'golang' } }

            steps {                 
                // Create our project directory.
                sh 'cd ${GOPATH}/src'
                sh 'mkdir -p ${GOPATH}/src/MY_PROJECT_DIRECTORY'

                // Copy all files in our Jenkins workspace to our project directory.                
                sh 'cp -r ${WORKSPACE}/* ${GOPATH}/src/MY_PROJECT_DIRECTORY'

                // Copy all files in our "vendor" folder to our "src" folder.
                sh 'cp -r ${WORKSPACE}/vendor/* ${GOPATH}/src'

                // Remove cached test results.
                sh 'go clean -cache'

                // Run Unit Tests.
                sh 'go test ./... -v -short'            
            }
        }      

        stage('Docker') {         
            environment {
                // Extract the username and password of our credentials into "DOCKER_CREDENTIALS_USR" and "DOCKER_CREDENTIALS_PSW".
                // (NOTE 1: DOCKER_CREDENTIALS will be set to "your_username:your_password".)
                // The new variables will always be YOUR_VARIABLE_NAME + _USR and _PSW.
                // (NOTE 2: You can't print credentials in the pipeline for security reasons.)
                DOCKER_CREDENTIALS = credentials('my-docker-credentials-id')
            }

            steps {                           
                // Use a scripted pipeline.
                script {
                    node {
                        def app

                        stage('Clone repository') {
                            checkout scm
                        }

                        stage('Build image') {                            
                            app = docker.build("${env.DOCKER_CREDENTIALS_USR}/my-project-img")
                        }

                        stage('Push image') {  
                            // Use the Credential ID of the Docker Hub Credentials we added to Jenkins.
                            docker.withRegistry('https://registry.hub.docker.com', 'my-docker-credentials-id') {                                
                                // Push image and tag it with our build number for versioning purposes.
                                app.push("${env.BUILD_NUMBER}")                      

                                // Push the same image and tag it as the latest version (appears at the top of our version list).
                                app.push("latest")
                            }
                        }              
                    }                 
                }
            }
        }
    }

    post {
        always {
            // Clean up our workspace.
            deleteDir()
        }
    }
}   

关于docker - Jenkins Golang 声明性管道 : Build Docker Image and Push to Docker Hub,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53264540/

相关文章:

http - 在请求进行中修改 golang Http Transport 是否安全?

mysql - 无法在 Google App Engine 中使用 MySQL Go Driver

jenkins - 在 Jenkins 中完成构建后触发相同的 jenkins 作业

java - 有选择地禁用每个环境的自动化案例

java - Docker 容器中的 OpenJDK 1.8.0 与/etc/timezone 和主机的时区不同

windows - GitHub 操作拉取 Windows 图像

go - 有没有更好的选择去使用常规 sleep

java - 如何解决 Spring Boot 上的 org.testcontainers.containers.ContainerFetchException?

docker - 我们可以在通过 dockerfile 构建 docker 镜像的同时通过 cmd 行传递 ENV 变量吗?

jenkins - 将新的本地用户添加到已配置 Active Directory 的 jenkins