ubuntu

Ubuntu Jenkins如何使用Docker容器

小樊
57
2025-09-18 19:36:06
栏目: 智能运维

Prerequisites
Before using Docker containers with Jenkins on Ubuntu, ensure Docker is installed and running. You can install Docker using the official repository:

sudo apt update
sudo apt install apt-transport-https ca-certificates curl gnupg-agent software-properties-common
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
sudo apt update
sudo apt install docker-ce docker-ce-cli containerd.io
sudo systemctl start docker
sudo systemctl enable docker

Verify Docker is running with docker --version and docker run hello-world.

1. Deploy Jenkins Using Docker
To quickly set up Jenkins, pull the official jenkins/jenkins:lts (Long-Term Support) image and run it as a container. The key flags are:

Command:

docker run -d -p 8080:8080 -p 50000:50000 --name jenkins -v jenkins_home:/var/jenkins_home jenkins/jenkins:lts

If you prefer local directory persistence (e.g., /opt/jenkins_home), replace the volume flag with -v /opt/jenkins_home:/var/jenkins_home.

2. Access and Initial Setup

3. Configure Jenkins to Use Docker
To allow Jenkins to control Docker (e.g., build/push images, run containers), grant it access to the Docker daemon:

This setup enables Jenkins to interact with Docker for tasks like building images from pipelines.

4. Create a Jenkins Pipeline with Docker
Use a Jenkinsfile to define a pipeline that leverages Docker for building/testing applications. Below is an example for a Node.js app:

5. Optional: Use Docker-in-Docker (DinD)
For advanced scenarios (e.g., isolating Docker operations within the Jenkins container), use DinD. This involves:

Example docker run command for DinD:

docker run --name jenkins -u root -d -p 8080:8080 -p 50000:50000 \
  -v /var/jenkins_home:/var/jenkins_home \
  -v /var/run/docker.sock:/var/run/docker.sock \
  -v /usr/bin/docker:/usr/bin/docker \
  jenkins/jenkins:lts

Note: DinD can introduce security risks (e.g., container breakout) and performance overhead. Use it only if necessary, and ensure proper isolation (e.g., use a dedicated Docker daemon for Jenkins).

Troubleshooting Tips

0
看了该问题的人还看了