search
HomeJavajavaTutorialKubernetes service--a brief example of running a single-instance stateful service

Goal

Create a PV in your environment
Create a Deployment of MySQl
Start by exposing MySQL to other pods using DNS names in the cluster

Previously

You need aKubernetes cluster and a kubectl command line tool that can connect to the cluster. If you don't have a cluster, you can use Minikube to create one.
We will create a PV (PersistentVolume) for data storage. Click here to view the supported PV types. This guide will use GCEPersistentDisk to demonstrate, but any PV type will work normally. GCEPersistentDisk only works on Google Compute Engine (GCE).

Create the disk in your environment

## In Google Compute Engine, run:

gcloud compute disks create --size=20GB mysql-disk

Then create a PV pointing to the mysql-disk just created. The following is a configuration file for creating a PV, pointing to the GCE disk mentioned above:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: mysql-pv
spec:
  capacity:
    storage: 20Gi
  accessModes:- ReadWriteOnce
  gcePersistentDisk:
    pdName: mysql-disk
    fsType: ext4

Note that the line pdName: mysql-disk matches the GCE environment creation disk above The name. If you want to create PVs in other environments, you can check out Persistent Volumes for details.
Create PV:

kubectl create -f https://k8s.io/docs/tasks/run-application/gce-volume.yaml

Deploy MySQL

You can create a stateful service through Kubernetes Deployment, and then use PVC (PersistentVolumeClaim) to connect to the existing PV. For example, the following YAML file describes a Deployment that runs MySQL and uses PVC. The file defines a volume mounted to /var/lib/mysql and creates a PVC that requires a 20G volume size.
Note: The password is defined in the YAML configuration file, which is not safe. Check out Kubernetes Secrets for more secure solutions.

apiVersion: v1
kind: Service
metadata:
  name: mysql
spec:
  ports:- port: 3306
  selector:
    app: mysql
  clusterIP: None---apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: mysql-pv-claim
spec:
  accessModes:- ReadWriteOnce
  resources:
    requests:
      storage: 20Gi---apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: mysql
spec:
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        app: mysql
    spec:
      containers:      - image: mysql:5.6name: mysql
        env:
          # Use secret in real usage- name: MYSQL_ROOT_PASSWORD
          value: password
        ports:- containerPort: 3306  name: mysql
        volumeMounts:- name: mysql-persistent-storage
          mountPath: /var/lib/mysql
      volumes:      - name: mysql-persistent-storage
        persistentVolumeClaim:
          claimName: mysql-pv-claim

1. Deploy the content in the YAML file.

kubectl create -f https://k8s.io/docs/tasks/run-application/mysql-deployment.yaml

2. Display Deployment information.

kubectl describe deployment mysql

 Name:                 mysql
 Namespace:            default
 CreationTimestamp:    Tue, 01 Nov 2016 11:18:45 -0700
 Labels:               app=mysql
 Selector:             app=mysql
 Replicas:             1 updated | 1 total | 0 available | 1 unavailable
 StrategyType:         Recreate
 MinReadySeconds:      0
 OldReplicaSets:       <none>
 NewReplicaSet:        mysql-63082529 (1/1 replicas created)
 Events:
   FirstSeen    LastSeen    Count    From                SubobjectPath    Type        Reason            Message   ---------    --------    -----    ----                -------------    --------    ------            -------
   33s          33s         1        {deployment-controller }             Normal      ScalingReplicaSet Scaled up replica set mysql-63082529 to 1</none>

3. Display the pods created by Deployment.

kubectl get pods -l app=mysql

 NAME                   READY     STATUS    RESTARTS   AGE
 mysql-63082529-2z3ki   1/1       Running   0          3m

4. Check PV.

 kubectl describe pv mysql-pv

 Name:            mysql-pv
 Labels:          <none>
 Status:          Bound
 Claim:           default/mysql-pv-claim
 Reclaim Policy:  Retain
 Access Modes:    RWO
 Capacity:        20Gi
 Message:    
 Source:
     Type:        GCEPersistentDisk (a Persistent Disk resource in Google Compute Engine)
     PDName:      mysql-disk
     FSType:      ext4
     Partition:   0 ReadOnly:    false
 No events.</none>

5. Check the PVC.

 kubectl describe pvc mysql-pv-claim

 Name:         mysql-pv-claim
 Namespace:    default
 Status:       Bound
 Volume:       mysql-pv
 Labels:       <none>
 Capacity:     20Gi
 Access Modes: RWO
 No events.</none>

Access MySQL instance

Previous YAML file Created a service that allows other Pods in the cluster to access the database. The service option clusterIP:None causes the service's DNS name to be resolved directly to the Pod's IP address. This is the best way to use it when your service only has one Pod and you don't plan to increase the number of Pods.
Run a Mysql client to connect to the Mysql service:

kubectl run -it --rm --image=mysql:5.6 mysql-client -- mysql -h <pod-ip> -ppassword</pod-ip>

The above command creates a new Pod in the cluster , the Pod runs a mysql client and is connected to the Mysql Server served above. If it connects successfully, it means that the stateful MySQL database is successfully up and running.

Waiting for pod default/mysql-client-274442439-zyp6i to be running, status is Pending, pod ready: falseIf you don't see a command prompt, try pressing enter.mysql>

Update

Update the image or other parts of the Deployment and you can use it as usual kubectl apply command to complete. The following are things to note when using stateful applications:

Do not expand the application. This application is only for singleton applications. The following PV can only be mapped to one Pod. For clustered stateful applications, check out the StatefulSet documentation.
Use strategy: type: Recreate in the Deployment’s YAML configuration document. It will tell Kubernetes not to use rolling update. Because Rolling update won't work, there won't be multiple Pods running at the same time. The strategy Recreate will delete the previous Pod when creating a new Pod with updated configuration.

Delete Deployment

Delete the Deployment object by name:

kubectl delete deployment,svc mysql
kubectl delete pvc mysql-pv-claim
kubectl delete pv mysql-pv

另外,如果你使用的是GCE disk,还需要删除对应的disk:

gcloud compute disks delete mysql-disk

 

文章转自:

The above is the detailed content of Kubernetes service--a brief example of running a single-instance stateful service. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Why is Java a popular choice for developing cross-platform desktop applications?Why is Java a popular choice for developing cross-platform desktop applications?Apr 25, 2025 am 12:23 AM

Javaispopularforcross-platformdesktopapplicationsduetoits"WriteOnce,RunAnywhere"philosophy.1)ItusesbytecodethatrunsonanyJVM-equippedplatform.2)LibrarieslikeSwingandJavaFXhelpcreatenative-lookingUIs.3)Itsextensivestandardlibrarysupportscompr

Discuss situations where writing platform-specific code in Java might be necessary.Discuss situations where writing platform-specific code in Java might be necessary.Apr 25, 2025 am 12:22 AM

Reasons for writing platform-specific code in Java include access to specific operating system features, interacting with specific hardware, and optimizing performance. 1) Use JNA or JNI to access the Windows registry; 2) Interact with Linux-specific hardware drivers through JNI; 3) Use Metal to optimize gaming performance on macOS through JNI. Nevertheless, writing platform-specific code can affect the portability of the code, increase complexity, and potentially pose performance overhead and security risks.

What are the future trends in Java development that relate to platform independence?What are the future trends in Java development that relate to platform independence?Apr 25, 2025 am 12:12 AM

Java will further enhance platform independence through cloud-native applications, multi-platform deployment and cross-language interoperability. 1) Cloud native applications will use GraalVM and Quarkus to increase startup speed. 2) Java will be extended to embedded devices, mobile devices and quantum computers. 3) Through GraalVM, Java will seamlessly integrate with languages ​​such as Python and JavaScript to enhance cross-language interoperability.

How does the strong typing of Java contribute to platform independence?How does the strong typing of Java contribute to platform independence?Apr 25, 2025 am 12:11 AM

Java's strong typed system ensures platform independence through type safety, unified type conversion and polymorphism. 1) Type safety performs type checking at compile time to avoid runtime errors; 2) Unified type conversion rules are consistent across all platforms; 3) Polymorphism and interface mechanisms make the code behave consistently on different platforms.

Explain how Java Native Interface (JNI) can compromise platform independence.Explain how Java Native Interface (JNI) can compromise platform independence.Apr 25, 2025 am 12:07 AM

JNI will destroy Java's platform independence. 1) JNI requires local libraries for a specific platform, 2) local code needs to be compiled and linked on the target platform, 3) Different versions of the operating system or JVM may require different local library versions, 4) local code may introduce security vulnerabilities or cause program crashes.

Are there any emerging technologies that threaten or enhance Java's platform independence?Are there any emerging technologies that threaten or enhance Java's platform independence?Apr 24, 2025 am 12:11 AM

Emerging technologies pose both threats and enhancements to Java's platform independence. 1) Cloud computing and containerization technologies such as Docker enhance Java's platform independence, but need to be optimized to adapt to different cloud environments. 2) WebAssembly compiles Java code through GraalVM, extending its platform independence, but it needs to compete with other languages ​​for performance.

What are the different implementations of the JVM, and do they all provide the same level of platform independence?What are the different implementations of the JVM, and do they all provide the same level of platform independence?Apr 24, 2025 am 12:10 AM

Different JVM implementations can provide platform independence, but their performance is slightly different. 1. OracleHotSpot and OpenJDKJVM perform similarly in platform independence, but OpenJDK may require additional configuration. 2. IBMJ9JVM performs optimization on specific operating systems. 3. GraalVM supports multiple languages ​​and requires additional configuration. 4. AzulZingJVM requires specific platform adjustments.

How does platform independence reduce development costs and time?How does platform independence reduce development costs and time?Apr 24, 2025 am 12:08 AM

Platform independence reduces development costs and shortens development time by running the same set of code on multiple operating systems. Specifically, it is manifested as: 1. Reduce development time, only one set of code is required; 2. Reduce maintenance costs and unify the testing process; 3. Quick iteration and team collaboration to simplify the deployment process.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool