jjzjj

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

coder 2023-06-30 原文

我正在尝试为我的 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/

有关docker - Jenkins Golang 声明性管道 : Build Docker Image and Push to Docker Hub的更多相关文章

  1. ruby-on-rails - active_admin 目录中的常量警告重新声明 - 2

    我正在使用active_admin,我在Rails3应用程序的应用程序中有一个目录管理,其中包含模型和页面的声明。时不时地我也有一个类,当那个类有一个常量时,就像这样:classFooBAR="bar"end然后,我在每个必须在我的Rails应用程序中重新加载一些代码的请求中收到此警告:/Users/pupeno/helloworld/app/admin/billing.rb:12:warning:alreadyinitializedconstantBAR知道发生了什么以及如何避免这些警告吗? 最佳答案 在纯Ruby中:classA

  2. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  3. ruby - 如何使用 method_missing 动态声明方法? - 2

    我有一个ruby​​程序,我想接受用户创建的方法,并使用该名称创建一个新方法。我试过这个:defmethod_missing(meth,*args,&block)name=meth.to_sclass我收到以下错误:`define_method':interningemptystring(ArgumentError)in'method_missing'有什么想法吗?谢谢。编辑:我以不同的方式让它工作,但我仍然很好奇如何以这种方式做到这一点。这是我的代码:defmethod_missing(meth,*args,&block)Adder.class_evaldodefine_method

  4. ruby-on-rails - Assets 管道损坏 : Not compiling on the fly css and js files - 2

    我开始了一个新的Rails3.2.5项目,Assets管道不再工作了。CSS和Javascript文件不再编译。这是尝试生成Assets时日志的输出:StartedGET"/assets/application.css?body=1"for127.0.0.1at2012-06-1623:59:11-0700Servedasset/application.css-200OK(0ms)[2012-06-1623:59:11]ERRORNoMethodError:undefinedmethod`each'fornil:NilClass/Users/greg/.rbenv/versions/1

  5. ruby-on-rails - 私有(private) gem 没有安装在 docker 中 - 2

    我正在尝试使用docker运行一个Rails应用程序。通过github的sshurl安装的gem很少,如下所示:Gemfilegem'swagger-docs',:git=>'git@github.com:xyz/swagger-docs.git',:branch=>'my_branch'我在docker中添加了keys,它能够克隆所需的repo并从git安装gem。DockerfileRUNmkdir-p/root/.sshCOPY./id_rsa/root/.ssh/id_rsaRUNchmod700/root/.ssh/id_rsaRUNssh-keygen-f/root/.ss

  6. ruby-on-rails - 将 Heroku 环境变量传输到 Docker 实例 - 2

    我在Heroku上构建了一个必须在Docker容器内运行的RoR应用程序。为此,我使用officialDockerfile.因为它在Heroku中很常见,所以我需要一些附加组件才能使这个应用程序完全运行。在生产中,变量DATABASE_URL在我的应用程序中可用。但是,如果我尝试其他一些使用环境变量(在我的例子中是Mailtrap)的加载项,变量不会在运行时复制到实例中。所以我的问题很简单:如何让docker实例在Heroku上执行时知道环境变量?您可能会问,我已经知道我们可以在docker-compose.yml中指定一个environment指令。我想避免这种情况,以便能够通过项目

  7. ruby - 更新 gem 时 Docker 包安装缓存问题 - 2

    我在开发和生产中都使用docker,真正困扰我的一件事是docker缓存的简单性。我的ruby​​应用程序需要bundleinstall来安装依赖项,因此我从以下Dockerfile开始:添加GemfileGemfile添加Gemfile.lockGemfile.lock运行bundleinstall--path/root/bundle所有依赖项都被缓存,并且在我添加新gem之前效果很好。即使我添加的gem只有0.5MB,从头开始安装所有应用程序gem仍然需要10-15分钟。由于依赖项文件夹的大小(大约300MB),然后再花10分钟来部署它。我在node_modules和npm上遇到了

  8. ruby-on-rails - 如何通过 Assets 管道加载css.erb文件 - 2

    我希望我的样式表保持纯css,但我想使用嵌入式ruby​​来包含一些图像的动态路径:.home{background:#FFFurl()no-repeat;}如果我将样式表从.css更改为.css.erb,image_path会得到正确解释,但当我部署到生产环境时,它不会被Assets管道处理。如果我硬编码路径,无论是在生产还是开发中都会出错,因为它们以不同的方式加载Assets。我该如何解决? 最佳答案 这是有效的:将.erb添加到.css文件并使用ruby/rails代码就可以了。所以我上面的问题中的片段很好。你必须在/conf

  9. 【详解】Docker安装Elasticsearch7.16.1集群 - 2

    开门见山|拉取镜像dockerpullelasticsearch:7.16.1|配置存放的目录#存放配置文件的文件夹mkdir-p/opt/docker/elasticsearch/node-1/config#存放数据的文件夹mkdir-p/opt/docker/elasticsearch/node-1/data#存放运行日志的文件夹mkdir-p/opt/docker/elasticsearch/node-1/log#存放IK分词插件的文件夹mkdir-p/opt/docker/elasticsearch/node-1/plugins若你使用了moba,直接右键新建即可如上图所示依次类推创建

  10. 转转测试环境docker化实践 - 2

        测试环境对于任何一个软件公司来讲,都是核心基础组件之一。转转的测试环境伴随着转转的发展也从单一的几套环境发展成现在的任意的docker动态环境+docker稳定环境环境体系。期间环境系统不断的演进,去适应转转集群扩张、新业务的扩展,走了一些弯路,但最终我们将系统升级到了我们认为的终极方案。下面我们介绍一下转转环境的演进和最终的解决方案。1测试环境演进1.1单体环境    转转在2017年成立之初,5台64G内存的机器,搭建5个完整的测试环境。就满足了转转的日常所需。一台分给开发,几台分给测试。通过沟通协调就能解决多分支并行开发下冲突问题。1.2动态环境+稳定环境    随着微服务化的进

随机推荐