---
title: "Deploying Next.js to Kubernetes on Ubuntu with Jenkins"
description: "A detailed guide to integrating Jenkins and Kubernetes on Ubuntu Linux to build a complete CI/CD pipeline for pulling code from GitHub, building a Docker image, pushing to a registry, and automatically deploying a Next.js application."
canonical_url: "https://blog.markkulab.net/en/post/jenkins-deploy-nextjs-to-ubuntu-kubernetes"
author: "Mark Ku"
author_url: "https://blog.markkulab.net/en/author/mark-ku"
site: "Mark Ku's Tech Notes"
date_published: "2024-11-17 01:01:35 +0800"
category: "DevOps"
tags: ["kubernetes", "docker", "ubuntu", "jenkins", "next.js", "pipeline", "ci/cd"]
language: "en"
license: "CC BY 4.0"
license_url: "https://creativecommons.org/licenses/by/4.0/"
attribution: "when reusing or quoting, credit the author and link back to the original"
---

# Deploying Next.js to Kubernetes on Ubuntu with Jenkins

## Introduction

[I've previously explored integrating Jenkins with Kubernetes on Windows Desktop](https://blog.markkulab.net/jenkins-deploy-kubernetes-with-docker-for-windows/), and this time, I'm going to try integrating Jenkins with Kubernetes on Linux.

## Prerequisites
* Docker, Kubernetes, and a Registry installed on Ubuntu
* Jenkins
* A Next.js project with its YAML configuration file ready.

## First, Install Kubernetes Dashboard, Generate a ServiceAccount, and Get the Token (this token will be used by Jenkins)
### Install Kubernetes Dashboard
```bash
kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/v2.7.0/aio/deploy/recommended.yaml
```
### Create an admin user
```bash
sudo vim dashboard-adminuser.yaml
```
### Create an admin user
```yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: admin-user
  namespace: kubernetes-dashboard

---

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: admin-user
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
subjects:
  - kind: ServiceAccount
    name: admin-user
    namespace: kubernetes-dashboard
```

### Create service account
```bash
kubectl apply -f dashboard-adminuser.yaml
```

### Get admin token
```bash
kubectl -n kubernetes-dashboard create token admin-user  --duration=876000h

```
### Start the Proxy
```
kubectl proxy
```

### You can now visit the following link to log in to the Dashboard
```
http://localhost:8001/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/#/login 
```
![dashboard](https://blog.markkulab.net/content/markku/posts/jenkins-deploy-nextjs-to-ubuntu-kubernetes/images/dashboard.png)

### Install Jenkins
Refer to my previous [article](https://blog.markkulab.net/docker-jenkins-build-docker-image-and-github-integration/) for instructions.

### Install kubectl in the Jenkins container
```bash
docker exec -it -uroot jenkins bash // 進入jenkins 容器中
curl -LO https://storage.googleapis.com/kubernetes-release/release/v1.29.1/bin/linux/amd64/kubectl // 下載 kubectl
chmod +x ./kubectl // 給予權限
mv ./kubectl /usr/local/bin/kubectl // 複製到系統環境資料夾
kubectl version --client // 查詢版本
```
P.S. It's best if the kubectl versions on Ubuntu and in the Jenkins container match.

### Copy kubectl configuration to the Jenkins container (execute line by line)
```bash
docker exec -it -uroot jenkins /bin/bash 
mkdir -p /.kube
exit 
docker cp ~/.kube/config jenkins:/root/.kube 
```

### Connect Jenkins to Kubernetes via the Kubernetes CLI
1. To connect Jenkins to Kubernetes, you need to install a few plugins. Go to Manage Jenkins > Manage Plugins.
* Kubernetes plugin
* Kubernetes CLI Plugin
![install kubernetes plugin](https://blog.markkulab.net/content/markku/posts/jenkins-deploy-nextjs-to-ubuntu-kubernetes/images/install-kubernetes-plugin.png)
2. [Set up cloud](http://localhost:8080/configureClouds/)
![set up cloud](https://blog.markkulab.net/content/markku/posts/jenkins-deploy-nextjs-to-ubuntu-kubernetes/images/set-cloud.png)
3. Set Disable https certificate check => true

![disable http certificate check](https://blog.markkulab.net/content/markku/posts/jenkins-deploy-nextjs-to-ubuntu-kubernetes/images/disable-http-certificate-check.png)
4. Kubernetes URL =>
On Ubuntu, you can find the URL with `kubectl cluster-info`.
![disable http certificate check](https://blog.markkulab.net/content/markku/posts/jenkins-deploy-nextjs-to-ubuntu-kubernetes/images/kubectl cluster-info.png.png)
```
https://192.168.50.50:6443  // 192.168.50.50是我家的Ubuntu 內網的主機IP
```
5. Jenkins URL
Jenkins URL:http://host.docker.internal:8080/
Jenkins tunnel:https://192.168.50.50:50000
6. Credentials =>
![add public key to jenkins](https://blog.markkulab.net/content/markku/posts/jenkins-deploy-nextjs-to-ubuntu-kubernetes/images/add-public-key-to-jenkins.png)
7. Copy dashboard token to here
![Copy dashboard token to here](https://blog.markkulab.net/content/markku/posts/jenkins-deploy-nextjs-to-ubuntu-kubernetes/images/copy-dashboard-token-to-here.png)

### Write the Jenkins pipeline
```groovy
properties([pipelineTriggers([githubPush()])])
pipeline {
    agent any 

    environment {
        tag = ':latest'
        imageShortName = 'k8s-next-ec'
        imageName = "${imageShortName}${tag}"
        containerName = "${imageShortName}-1"        
        dockerfile = "./Dockerfile"        
        registryUrl = "192.168.50.50:5000"
        registry = "${registryUrl}/${imageShortName}"
        
    }   
   
    stages {
        stage("GitHub Pull") {
             steps {
                git branch: 'main', 
                credentialsId: 'e85233ad-a3c5-448b-a6ea-9f53e4f9b3f1', 
                url:  'git@github.com:markku636/ec.git/'
            }
            
        }
        
          stage("Building Docker Image") {
			steps {
				script {
					dockerImage = docker.build "$registry${tag}"
				}
			}
		}
		
		stage("Deploying to Registry Server") {
			steps {
			    script {
				    docker.withRegistry("","") {
					  dockerImage.push("latest")
					}
			    }
			}
		}
        
        stage("Cleaning Up") {
            steps {
                sleep(time: 3, unit: "SECONDS")

                sh "docker rmi --force $registry:latest"
            }
        }                   
        
        stage("Deply") {
             steps {
                    withKubeConfig([credentialsId: 'k8s-secret', serverUrl: 'https://192.168.50.50:6443']) {                     
                     sh 'kubectl apply -f ./next-js-deployment.yaml'
					 sh 'kubectl rollout restart deployment/k8s-next-ec'
                    }
                
             }
        }                         
    }
}
```

## Create the Kubernetes YAML deployment configuration file (next-js-deployment.yaml) in the Github next-ec project
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: k8s-next-ec
  labels:
    app: k8s-next-ec
spec:
  selector:
    matchLabels:
      app: k8s-next-ec
      tier: web
  template:
    metadata:
      labels:
        app: k8s-next-ec
        tier: web
    spec:
      containers:
      - name: k8s-next-ec-app
        image: 192.168.50.50:5000/k8s-next-ec:latest
        ports:
        - containerPort: 3000            
---

apiVersion: v1
kind: Service
metadata:
  name: k8s-next-ec
  labels:
    app: k8s-next-ec
spec:
  selector:
    app: k8s-next-ec
  type: NodePort
  ports:
    - name: http
      protocol: TCP
      port: 3000
      targetPort: 3000
      nodePort: 30066

```

Now, run the build in Jenkins, and you should see it succeed.
![Jenkins build result](https://blog.markkulab.net/content/markku/posts/jenkins-deploy-nextjs-to-ubuntu-kubernetes/images/final.png)

## Appendix - If you encounter a permission error like the one below

ERROR: permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Head "http://%2Fvar%2Frun%2Fdocker.sock/_ping": dial unix /var/run/docker.sock: connect: permission denied
Quick fix
```bash
sudo chmod 777 /var/run/docker.sock
```

Permanent fix

```
sudo nano /etc/systemd/system/docker-sock-permission.service
```

```
[Unit]
Description=Set permission on /var/run/docker.sock
After=docker.service
Requires=docker.service

[Service]
Type=oneshot
ExecStart=/bin/chmod 777 /var/run/docker.sock
RemainAfterExit=true

[Install]
WantedBy=multi-user.target

```
Reload systemd and enable the service
```
sudo systemctl daemon-reexec
sudo systemctl daemon-reload
sudo systemctl enable docker-sock-permission.service
sudo systemctl start docker-sock-permission.service
sudo systemctl status docker-sock-permission.service
```

## References
* [Using the Kubernetes Dashboard GUI to Manage a Cluster](https://ciao-chung.com/page/article/kubernetes-dashboard-manage-cluster)
* [Upgrading Your Cloud Run CI/CD with Jenkins](https://manel-lemin.medium.com/upgrading-your-cloud-run-ci-cd-with-jenkins-92a3717e9f1c)
* [How to Deploy application on GKE using Jenkins](https://blog.knoldus.com/how-to-deploy-application-on-gke-using-jenkins/)

---

## About this article and its author

Originally published on [Mark Ku's Tech Notes](https://blog.markkulab.net/en/post/jenkins-deploy-nextjs-to-ubuntu-kubernetes)

License: [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) — when reusing or quoting, credit the author and link back to the original

### About the author

**[Mark Ku](https://blog.markkulab.net/en/author/mark-ku)** — Software Solution Provider

- 10+ years senior software engineer, now an AI Builder
- Focused on large-platform architecture — North-American e-commerce, AI SaaS subscription billing
- Combining AI Agents and automation to build evolvable product foundations

### Free tools built by the author

All of these are free to use:

- [Free PDF Sign Tool](https://blog.markkulab.net/en/tools/pdf-sign): Online PDF sign tool — draw, type, or upload a signature, then drag, resize, and download. Everything runs in your browser; nothing is uploaded.
- [VS Code Refactory](https://blog.markkulab.net/en/tools/refactory): Refactory is a VS Code refactoring extension: 34 actions plus a 37-rule code-smell inspection layer with a Code Health dashboard, across 18 languages, backed by 534 tests. It learns your repo's conventions: where interfaces live, where DI is registered, whether 'use client' belongs. It ranks files by git churn × complexity so you know what to fix first, and hands any smell to the Claude Code already on your machine. Free to use, and your source never leaves your computer.
- [DB-Kit Database Manager](https://blog.markkulab.net/en/tools/db-kit): DB-Kit is a lightweight, cross-platform database manager built with Tauri + Rust + React. Manage MySQL, MariaDB, PostgreSQL, SQL Server, Oracle, SQLite, MongoDB, Redis, Kafka, Elasticsearch and RabbitMQ from one consistent interface: passwords encrypted in the OS keychain, SSH tunnels, full CRUD, a visual query builder, stacked multi-statement result sets, cross-connection data transfer and compare/sync, Excel / CSV import & export, visualized execution plans, ER diagrams, scheduled backups, SQL stress testing with p50–p99 latency percentiles, a 15-rule SQL review engine, Kafka message browsing with monitoring & alerts, a bilingual UI (Traditional Chinese / English), a built-in AI assistant (natural-language SQL, AI review and tuning advice) and the dbk CLI. Free and open source (MIT), with installers for Windows, macOS and Linux.
- [VS Code Super Mermaid](https://blog.markkulab.net/en/tools/super-mermaid): Super Mermaid is a VS Code extension for beautiful Mermaid diagrams out of the box: auto-colored live preview, mouse pan & zoom, high-res PNG / SVG export, 21 templates and multiple themes. Free and open source (MIT).
- [React Super Mermaid](https://blog.markkulab.net/en/tools/react-super-mermaid): react-super-mermaid is an open-source React component library: render beautiful Mermaid diagrams with a single <MermaidViewer>, with built-in colorful / sketch themes, pan & zoom, in-diagram search, and high-res SVG / PNG export. Lightweight, SSR-safe, fully typed. Free and open source (MIT).
- [Jira / Confluence Super Mermaid](https://blog.markkulab.net/en/tools/jira-super-mermaid): An Atlassian Forge app: write Mermaid syntax directly inside a Jira issue or a Confluence page and get flowcharts, sequence diagrams, state machines and Gantt charts. 11 diagram types, SVG / PNG export, light and dark themes, full CJK support. Runs on Atlassian: your diagrams live in your own site and the app calls no third-party service. Free, coming soon to the Atlassian Marketplace.
- [Mermaid Live Preview](https://blog.markkulab.net/en/tools/mermaid-preview): Write Mermaid in your browser, see it render instantly, and share the whole diagram as a single link. No sign-up, nothing uploaded to a server, and mermaid.live share links work as-is.
- [React Intl Phone Number](https://blog.markkulab.net/en/tools/react-intl-phone-number): react-intl-phone-number is an open-source React component: framework-agnostic and antd-free, with E.164 in/out, a searchable flag / country-code dropdown, configurable validation levels (strict / mobile-strict / loose), themeable CSS, and i18n — phone logic powered by google-libphonenumber. Lightweight and fully typed. Free and open source (MIT).
- [Uptime Kuma Cluster](https://blog.markkulab.net/en/tools/uptime-kuma-cluster): Turn single-node Uptime Kuma into a highly available cluster: OpenResty + Lua smart load balancing, shared MariaDB state, health checks and automatic failover, plus cluster-management REST APIs. One Docker Compose command to start. Free and open source (MIT).
- [Special Education](https://blog.markkulab.net/en/education): Learning materials crafted for special education students

### Daily podcasts

- [Mark's Tech Insights — Daily AI News](https://blog.markkulab.net/en/category/tech-news): Daily curated AI and tech trends. Catch the latest developments via audio summaries — covering AI applications, software architecture, DevOps, and engineering practice. — RSS: https://blog.markkulab.net/feed.xml
- [AI股市蝦聊](https://blog.markkulab.net/en/category/ai-stock-chat): Every trading day, an AI-analyzed take on the Taiwan stock market, delivered as a two-host conversation covering the session and the next-day outlook. — RSS: https://blog.markkulab.net/ai-stock-chat/feed.xml
- [開源好物週報](https://blog.markkulab.net/en/category/open-source-weekly): A weekly two-host pick of free open-source tools surfaced from real Hacker News, GitHub, and Reddit buzz — what pain they solve and the fastest way to get started. — RSS: https://blog.markkulab.net/open-source-weekly/feed.xml

### Newsletter

[Subscribe to the newsletter](https://blog.markkulab.net/en/subscribe) — Be the first to know about new posts. No spam, unsubscribe anytime.
