Kubernetes:如何在Kubernetes中部署REST API

This blog will help you get started on deploying your REST API in Kubernetes. First, we'll set up a local Kubernetes cluster, then create a simple API to deploy.
本博客将帮助您开始在Kubernetes中部署REST API。首先,我们将设置一个本地Kubernetes集群,然后创建一个简单的API来部署。

There are already a lot of free resources available explaining basic Kubernetes concepts, so go check those out first if you haven't already. This blog is intended for beginners but assumes you already have a basic understanding of Kubernetes and Docker concepts.
已经有很多免费的资源可以解释基本的Kubernetes概念,所以如果你还没有的话,先去看看这些资源。本博客面向初学者,但假设您已经对Kubernetes和Docker概念有了基本的了解。

1. Set Up Local Kubernetes 【设置本地Kubernetes】

There's a couple options for running Kubernetes locally, with the most popular ones including minikubek3skindmicrok8s. In this guide, any of these will work, but we will be using k3s because of the lightweight installation.
在本地运行Kubernetes有几个选项,最受欢迎的包括minikube,k3 s,kind,microk 8 s。在本指南中,所有这些都可以工作,但我们将使用k3 s,因为它是轻量级安装。

Install k3d, which is a utility for running k3s. k3s will be running in Docker, so make sure you have that installed as well. We used k3d v4.0 in this blog.
安装k3d,这是一个运行k3s的实用程序。k3s将在Docker中运行,因此请确保您也安装了它。我们在这个博客中使用了k3d v4.0。

curl -s https://raw.githubusercontent.com/rancher/k3d/main/install.sh | bash

Set up a cluster named test:
设置名为test的群集:

  • The port flag is for mapping port 80 from our machine to port 80 on the k3s load balancer. This is needed later when we use ingress.
    端口标志用于将我们机器上的端口80映射到k3s负载均衡器上的端口80。这在后面使用ingress时是需要的。
k3d cluster create test -p "80:80@loadbalancer"

Optionally, check that your kubeconfig got updated and the current context is correct:
可选地,检查您的kubeconfig是否已更新,并且当前上下文是否正确:

kubectl config view
kubectl config current-context

Optionally, confirm that k3s is running in Docker. There should be two containers up, one for k3s and the other for load balancing:
可选地,确认k3s正在Docker中运行。应该有两个容器,一个用于k3s,另一个用于负载平衡:

docker ps

Make sure that all the pods are running. If they are stuck in pending status, it may be that there is not enough disk space on your machine. You can get more information by using the describe command:
确保所有pod都在运行。如果它们停留在挂起状态,则可能是计算机上没有足够的磁盘空间。您可以使用describe命令获取更多信息:

kubectl get pods -A
kubectl describe pods -A

There's a lot of kubectl commands you can try, so I recommend checking out the list of resources and being aware of their short names:
有很多kubectl命令可以尝试,所以我建议查看资源列表并注意它们的短名称:

kubectl api-resources

2. Create a Simple API 【创建简单API】

We will create a simple API using Express.js.
我们将使用Express.js创建一个简单的API。

Set up the project: 设置项目:

mkdir my-backend-api && cd my-backend-api
touch server.js
npm init
npm i express --save
// server.js
const express = require("express");
const app = express();

app.get("/user/:id", (req, res) => {
  const id = req.params.id;
  res.json({
    id,
    name: `John Doe #${id}`
  });
});

app.listen(80, () => {
  console.log("Server running on port 80");
});

Optionally, you can try running it if you have Node.js installed and test the endpoint /user/{id} with curl:
可选地,如果你安装了Node.js,你可以尝试运行它,并使用curl测试端点/user/{id}:

node server.js

// request:
curl http://localhost:80/user/123

// response: {"id":"123","name":"John Doe #123"}

Next, add a Dockerfile and .dockerignore:
接下来,添加一个Dockerfile和.dockerignore:

// Dockerfile
FROM node:12

WORKDIR /usr/src/app
COPY package*.json ./
RUN npm i
COPY . .

EXPOSE 80
CMD ["node", "server.js"]
// .dockerignore
node_modules

Then, build the image and push it to the Docker Hub registry:
然后,构建镜像并将其推送到Docker Hub注册表:

  • If you want to skip this step, you can use the existing image here.
    如果你想跳过这一步,你可以使用现有的图像在这里。
docker build -t <YOUR_DOCKER_ID>/my-backend-api .
docker push <YOUR_DOCKER_ID>/my-backend-api

3. Deploy【部署】

Now, we deploy the image to our local Kubernetes cluster. We use the default namespace.
现在,我们将映像部署到本地Kubernetes集群。我们使用默认的命名空间。

Create a deployment: 创建展开:

kubectl create deploy my-backend-api --image=andyy5/my-backend-api
  • Alternatively, create a deployment with a YAML file:
    或者,使用YAML文件创建展开:
kubectl create -f deployment.yaml
// deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-backend-api
  labels:
    app: my-backend-api
spec:
  replicas: 1
  selector:
    matchLabels:
      app: my-backend-api
  template:
    metadata:
      labels:
        app: my-backend-api
    spec:
      containers:
      - name: my-backend-api
        image: andyy5/my-backend-api

Create a service: 创建服务:

kubectl expose deploy my-backend-api --type=ClusterIP --port=80
  • Alternatively, create a service with a YAML file:
    或者,使用YAML文件创建服务:
kubectl create -f service.yaml
// service.yaml
apiVersion: v1
kind: Service
metadata:
  name: my-backend-api
  labels:
    app: my-backend-api
spec:
  type: ClusterIP
  ports:
  - port: 80
    protocol: TCP
    targetPort: 80
  selector:
    app: my-backend-api

Check that everything was created and the pod is running:
检查是否已创建所有内容以及Pod是否正在运行:

kubectl get deploy -A
kubectl get svc -A
kubectl get pods -A

Once the pod is running, the API is accessible within the cluster only. One quick way to verify the deployment from our localhost is by doing port forwarding:
一旦pod运行,API只能在集群内访问。从本地主机验证部署的一种快速方法是执行端口转发:

  • Replace the pod name below with the one in your cluster
    将下面的pod名称替换为集群中的名称
kubectl port-forward my-backend-api-84bb9d79fc-m9ddn 3000:80
  • Now, you can send a curl request from your machine
    现在,您可以从您的机器发送curl请求
curl http://localhost:3000/user/123

To correctly manage external access to the services in a cluster, we need to use ingress. Close the port-forwarding and let's expose our API by creating an ingress resource.
为了正确管理对集群中服务的外部访问,我们需要使用ingress。关闭端口转发,让我们通过创建一个入口资源来公开我们的API。

  • An ingress controller is also required, but k3d by default deploys the cluster with a Traefik ingress controller (listening on port 80).
    还需要一个入口控制器,但k3d默认使用Traefik入口控制器(侦听端口80)部署集群。
  • Recall that when we created our cluster, we set a port flag with the value "80:80@loadbalancer". If you missed this part, go back and create your cluster again.
    回想一下,当我们创建集群时,我们设置了一个值为“80:80@loadbalancer”的端口标志。如果您错过了这一部分,请返回并重新创建集群。

Create an Ingress resource with the following YAML file:
使用以下YAML文件创建Ingress资源:

kubectl create -f ingress.yaml
kubectl get ing -A
// ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: my-backend-api
  annotations:
    ingress.kubernetes.io/ssl-redirect: "false"
spec:
  rules:
  - http:
      paths:
      - path: /user/
        pathType: Prefix
        backend:
          service:
            name: my-backend-api
            port:
              number: 80
  • Now try it out! 现在试试吧!
curl http://localhost:80/user/123

If you want to learn more on how to deploy using a managed Kubernetes service in the cloud, such as Google Kubernetes Engine, then check out the excellent guides on the official Kubernetes docs.
如果您想了解更多关于如何在云中使用托管Kubernetes服务(如Google Kubernetes Engine)进行部署的信息,请查看官方Kubernetes文档上的优秀指南。




How to Deploy a REST API in Kubernetes | LoginRadius Blog

kube-apiserver · Kubernetes指南

https://www.cnblogs.com/elnino/p/9578017.html

k8s部署restful服务_flask_restful k8s_小夏小夏要坚强的博客-CSDN博客

猜你喜欢

转载自blog.csdn.net/u013250861/article/details/130143457