You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

咨询:基于Jenkins、Docker与Minikube的Kubernetes全CI/CD流水线搭建

Hey Aziz, great question! Since you’re already comfortable with Jenkins + GitHub + Elastic Beanstalk, transitioning to a Jenkins → Docker → Minikube CI/CD pipeline is totally manageable. Let’s break this down into actionable, beginner-friendly steps:

1. Prerequisites & Environment Prep

First, make sure your foundational tools are set up and connected:

  • Confirm Minikube is running: minikube start (verify with minikube status)
  • Link Jenkins to your Minikube cluster:
    • If Jenkins and Minikube are on the same machine, copy your local ~/.kube/config file to Jenkins’ home directory (/var/lib/jenkins/.kube/config) and give Jenkins read access to it.
    • If Jenkins is remote, transfer the kubeconfig file to the Jenkins server and place it in ~jenkins/.kube/.
  • Optional but recommended: Use Minikube’s built-in Docker daemon. This lets you build images directly in Minikube’s environment (no need to push to an external registry). Run eval $(minikube docker-env) to point your shell to Minikube’s Docker—you can add this as an environment variable in Jenkins for global access.
2. Install Critical Jenkins Plugins

Head to Jenkins’ Manage Jenkins → Plugins and install these:

  • Docker Pipeline: Handles Docker image builds within your pipeline
  • Kubernetes CLI Plugin: Lets Jenkins run kubectl commands to interact with Minikube
  • Credentials Binding Plugin: Safely manages Docker Hub or registry credentials (if you use external image storage)
  • You’ll already have the Git Plugin from your GitHub work—just ensure it’s updated.
3. Configure Jenkins for Minikube Access
  • Go to Manage Jenkins → Configure System → Kubernetes CLI
  • Add a new cluster configuration, select the "kubeconfig" option, and point it to the config file you copied earlier. Test the connection to confirm Jenkins can talk to Minikube.
4. Build Docker Images (Two Options)

Option 1: Build Directly in Minikube (No Registry Needed)

This is the simplest path for local Minikube setups:

  1. Create a Dockerfile in your project root (example for a Node.js app):
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]
  1. In your Jenkins pipeline, add a stage to build the image:
stage('Build Docker Image') {
    steps {
        sh 'eval $(minikube docker-env)'
        sh 'docker build -t my-app:${BUILD_NUMBER} .'
    }
}

Note: Add the Jenkins user to the docker group with sudo usermod -aG docker jenkins and restart Jenkins to fix permission issues.

Option 2: Push to Docker Hub (For Future Remote Clusters)

If you plan to move to a remote Kubernetes cluster later, use Docker Hub:

  1. Add your Docker Hub credentials to Jenkins (Manage Jenkins → Credentials) as a "Username with password" entry.
  2. Update your pipeline stage to login, build, and push:
stage('Build & Push Docker Image') {
    steps {
        withCredentials([usernamePassword(credentialsId: 'docker-hub-creds', usernameVariable: 'DOCKER_USER', passwordVariable: 'DOCKER_PASS')]) {
            sh 'docker login -u $DOCKER_USER -p $DOCKER_PASS'
            sh 'docker build -t $DOCKER_USER/my-app:${BUILD_NUMBER} .'
            sh 'docker push $DOCKER_USER/my-app:${BUILD_NUMBER}'
        }
    }
}
5. Kubernetes Deployment Configs

Create two YAML files in your project root to define your app’s deployment and service:

deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app-deployment
spec:
  replicas: 2
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
      - name: my-app
        image: my-app:${BUILD_NUMBER} # Replace with Docker Hub path if using Option 2
        ports:
        - containerPort: 3000
        resources:
          requests:
            cpu: "100m"
            memory: "128Mi"
          limits:
            cpu: "200m"
            memory: "256Mi"

service.yaml

apiVersion: v1
kind: Service
metadata:
  name: my-app-service
spec:
  type: NodePort # Lets you access the app via Minikube's IP
  selector:
    app: my-app
  ports:
    - protocol: TCP
      port: 80
      targetPort: 3000
6. Full Jenkins Pipeline (Jenkinsfile)

Save this as Jenkinsfile in your GitHub repo root—Jenkins will pull it automatically:

pipeline {
    agent any
    environment {
        IMAGE_TAG = "${BUILD_NUMBER}"
        IMAGE_NAME = "my-app:${IMAGE_TAG}"
    }
    stages {
        stage('Checkout Code') {
            steps {
                git url: 'https://github.com/your-username/your-repo.git', branch: 'main'
            }
        }
        stage('Build Docker Image') {
            steps {
                sh 'eval $(minikube docker-env)'
                sh 'docker build -t ${IMAGE_NAME} .'
            }
        }
        stage('Deploy to Minikube') {
            steps {
                // Replace the image tag in deployment.yaml
                sh 'sed -i "s|my-app:.*|${IMAGE_NAME}|" deployment.yaml'
                // Apply Kubernetes configs
                sh 'kubectl apply -f deployment.yaml'
                sh 'kubectl apply -f service.yaml'
                // Wait for deployment to finish
                sh 'kubectl rollout status deployment/my-app-deployment'
            }
        }
        stage('Test Deployment') {
            steps {
                script {
                    def minikubeIp = sh(script: 'minikube ip', returnStdout: true).trim()
                    def servicePort = sh(script: 'kubectl get service my-app-service -o jsonpath="{.spec.ports[0].nodePort}"', returnStdout: true).trim()
                    sh "curl -s http://${minikubeIp}:${servicePort} | grep 'Expected App Content'"
                }
            }
        }
    }
    post {
        success {
            echo 'Deployment succeeded! 🎉'
        }
        failure {
            echo 'Deployment failed—check pod logs with `kubectl logs <pod-name>` for details!'
        }
    }
}
7. Set Up the Jenkins Job
  • Create a new Pipeline job in Jenkins
  • Under the Pipeline section, select "Pipeline script from SCM", choose Git, and enter your GitHub repo URL. Set the Jenkinsfile path to ./Jenkinsfile.
  • Add a GitHub webhook to trigger the pipeline automatically on code pushes (you know how to do this from your Elastic Beanstalk work!).
Pro Tips for K8s Newbies
  • Use minikube dashboard to visualize your cluster and debug deployments
  • If pods fail to start, run kubectl logs <pod-name> to check container logs
  • Always use unique image tags (like BUILD_NUMBER) to avoid caching issues
  • For complex apps, try Helm (a Kubernetes package manager) to simplify deployment management

内容的提问来源于stack exchange,提问作者Aziz Zoaib

火山引擎 最新活动