Continuous Integration (CI) and Continuous Deployment (CD) are essential practices in modern software development. This tutorial will guide you through setting up a CI/CD pipeline using Jenkins, Docker, and Git.
Prerequisites
- Basic knowledge of Linux commands
- Docker installed on your machine
- Jenkins installed and running
Step 1: Set up a Git Repository
Create a new Git repository for your project. You can use any Git hosting service like GitHub or GitLab.
git init
git add .
git commit -m "Initial commit"
git remote add origin <your-repository-url>
git push -u origin master
Step 2: Create a Dockerfile
Create a Dockerfile
in the root directory of your project. This file will define the base image, environment variables, and commands to build your Docker image.
FROM nginx:latest
COPY . /usr/share/nginx/html
Step 3: Configure Jenkins
- Install the Jenkins Pipeline Plugin from the Jenkins dashboard.
- Create a new Jenkins job with the Pipeline script syntax.
pipeline {
agent any
stages {
stage('Build') {
steps {
echo 'Building Docker image...'
script {
docker.image('my-image').build()
}
}
}
stage('Test') {
steps {
echo 'Running tests...'
// Add your test commands here
}
}
stage('Deploy') {
steps {
echo 'Deploying to production...'
// Add your deployment commands here
}
}
}
}
Step 4: Automate the CI/CD Pipeline
To automate the CI/CD pipeline, you can use Git hooks. In this example, we will use a pre-commit hook to trigger the Jenkins job.
- Clone your repository to a local machine.
- Navigate to the
.git/hooks
directory. - Create a new file named
pre-commit
and add the following content:
#!/bin/sh
# Trigger Jenkins job on commit
curl -X POST <your-jenkins-job-url>/buildWithParameters?token=<your-token>&参数1=值1&参数2=值2
- Make the
pre-commit
file executable:
chmod +x .git/hooks/pre-commit
Step 5: Test Your CI/CD Pipeline
Commit some changes to your repository and push them. The pre-commit hook should trigger the Jenkins job, running the build, test, and deployment stages.
By following this tutorial, you should now have a basic CI/CD pipeline set up for your project. This will help you automate your development process, ensure code quality, and streamline your deployment workflow. For more advanced configurations and features, you can refer to the Jenkins documentation.