pipeline { agent any tools{ gradle "gradle" } stages { stage('init') { steps { script{ def dockerPath = tool 'docker' //全局配置里的docker env.PATH = "${dockerPath}/bin:${env.PATH}" //添加了系统环境变量上 } } } stage('Build') { steps { script{ sh "docker --version" } } } } }
注意:我们需要把docker的路径添加到env环境变量里才可以使用docker命令,这个我试了很多次。
二 添加jenkins用户到docker组
上面的操作完成之后,你的 docker --version
是可以打印了,但还不能执行docker命令,还需要你把jenkins用户添加到 docker
用户组里。
docker run --rm -v /Users/Shared/Jenkins/Home/workspace/helloJava:/src --user root --privileged=true alpine:3.6 sh -c 'cp /src/src/main/docker/Dockerfile /src/build/libs' docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post http://%2Fvar%2Frun%2Fdocker.sock/v1.39/containers/create: dial unix /var/run/docker.sock: connect: permission denied.
当前用户添加到docker组
sudo gpasswd -a ${USER} docker #或者将当前用户直接加到文件中 sudo echo "docker:x:994:${USER}" >> /etc/group #查看docker用户组成员 cat /etc/group |grep docker #重新启动docker服务 sudo systemctl restart docker # 赋予权限 sudo chmod a+rw /var/run/docker.sock
sudo launchctl unload /Library/LaunchDaemons/org.jenkins-ci.plist sudo vim /Library/LaunchDaemons/org.jenkins-ci.plist sudo chown -R lind.zhang:docker /Users/Shared/Jenkins/ sudo chown -R lind.zhang:docker /var/log/jenkins/ 启动jenkins sudo launchctl load /Library/LaunchDaemons/org.jenkins-ci.plist
大功告成
[Pipeline] script [Pipeline] { [Pipeline] sh + docker run alpine:3.6 /bin/echo hello hello [Pipeline] } [Pipeline] // script [Pipeline] } [Pipeline] // withEnv [Pipeline] } [Pipeline] // stage [Pipeline] } [Pipeline] // withEnv [Pipeline] } [Pipeline] // withEnv [Pipeline] } [Pipeline] // node [Pipeline] End of Pipeline Finished: SUCCESS