Kind方式部署k8s单节点集群并创建nginx服务对外访问

资源要求

请准备好doker环境,尽量用比较新的版本。我的docker环境如下
docker 环境: Docker version 20.10.21, build 20.10.21-0ubuntu1~18.04.3

安装kind

kind表现上就是一个二进制程序,下载对应版本并增加执行权限即可:

curl -Lo ./kind https://kind.sigs.k8s.io/dl/v0.11.1/kind-linux-amd64
chmod +x ./kind
mv ./kind /usr/bin/kind
kind version

如何通过kind新建k8s集群?

kubectl是与k8s交互的客户端命令工具,因此需要先安装此工具。

curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl
kubectl version --client

使用config文件创建k8s集群

extraPortMappings:把K8s容器(相当于K8s所在的服务器)端口暴露出来,这里暴露了30000-30005,可以理解为把docker部署的k8s集群中的服务,通过docker服务将端口映射出来给到宿主机可以访问。

kind-config.yaml

kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
  - role: control-plane
    extraPortMappings:
      - containerPort: 30000
        hostPort: 30000
        protocol: TCP
      - containerPort: 30001
        hostPort: 30001
        protocol: TCP
      - containerPort: 30002
        hostPort: 30002
        protocol: TCP
      - containerPort: 30003
        hostPort: 30003
        protocol: TCP
      - containerPort: 30004
        hostPort: 30004
        protocol: TCP
      - containerPort: 30005
        hostPort: 30005
        protocol: TCP

使用以下命令来创建集群

kind create cluster --name myk8s-01 --config kind-config.yaml
To start using your cluster, you need to run the following as a regular user:

  mkdir -p $HOME/.kube
  sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
  sudo chown $(id -u):$(id -g) $HOME/.kube/config

Alternatively, if you are the root user, you can run:

  export KUBECONFIG=/etc/kubernetes/admin.conf

You should now deploy a pod network to the cluster.
Run "kubectl apply -f [podnetwork].yaml" with one of the options listed at:
  https://kubernetes.io/docs/concepts/cluster-administration/addons/

You can now join any number of control-plane nodes by copying certificate authorities
and service account keys on each node and then running the following as root:

  kubeadm join myk8s-01-control-plane:6443 --token <value withheld> \
        --discovery-token-ca-cert-hash sha256:fc1aad44ac2b0d95ce17a0ed081a336768da10492f8091aeaf6ebfa060a55cf0 \
        --control-plane

Then you can join any number of worker nodes by running the following on each as root:

kubeadm join myk8s-01-control-plane:6443 --token <value withheld> \
        --discovery-token-ca-cert-hash sha256:fc1aad44ac2b0d95ce17a0ed081a336768da10492f8091aeaf6ebfa060a55cf0
 ✓ Starting control-plane 🕹️
 ✓ Installing CNI 🔌
 ✓ Installing StorageClass 💾
Set kubectl context to "kind-myk8s-01"
You can now use your cluster with:

kubectl cluster-info --context kind-myk8s-01

Thanks for using kind! 😊

root@raypick:/home/raypick/k8s_resource/helen# docker ps
CONTAINER ID   IMAGE                  COMMAND                  CREATED          STATUS          PORTS                                                             NAMES
6b1f30ea4d28   kindest/node:v1.21.1   "/usr/local/bin/entr…"   25 minutes ago   Up 25 minutes   0.0.0.0:30000-30005->30000-30005/tcp, 127.0.0.1:41957->6443/tcp   myk8s-01-control-plane
root@raypick:/home/raypick/k8s_resource/helen#

创建完成后正常会在宿主机的目录下生成这个文件,/etc/kubernetes/admin.conf,如果没有的话,docker cp,将容器集群中的
/etc/kubernetes/admin.conf文件拷贝出来到宿主机的/etc/kubernetes目录下即可,但是记住拷贝的话需要修改修改其中的server为127.0.0.1,默认是docker网段中的ip地址

在这里插入图片描述

执行以下命令,将k8s集群配置加载进环境变量中,之后即可开始后续的内容操作

export KUBECONFIG=/etc/kubernetes/admin.conf

创建资源进行测试

namespace.yaml

apiVersion: v1
kind: Namespace
metadata:
  name: helen

serviceaccount.yaml

apiVersion: v1
kind: ServiceAccount
metadata:
  name: sa-helen
  namespace: helen

role.yaml

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: role-helen
  namespace: helen
rules:
- apiGroups: [""]
  resources:
    - pods
    - pods/exec
    - pods/log
    - services
    - endpoints
    - configmaps
    - secrets
    - persistentvolumeclaims
    - serviceaccounts
  verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
- apiGroups: ["apps"]
  resources:
    - deployments
    - replicasets
    - statefulsets
    - daemonsets
  verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
- apiGroups: ["batch"]
  resources:
    - jobs
    - cronjobs
  verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]


rolebinding.yaml

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: helen-sa-role-binding
  namespace: helen
subjects:
- kind: ServiceAccount
  name: sa-helen
  namespace: helen
roleRef:
  kind: Role
  name: role-helen
  apiGroup: rbac.authorization.k8s.io

secret-helen.yaml

apiVersion: v1
kind: Secret
metadata:
  name: helen-secret
  namespace: helen
type: Opaque
stringData:
  MYSQL_PASSWORD: mysql_pass
  SFTP_PASSWORD: sftp_pass

nginx.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  namespace: helen
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      serviceAccountName: sa-helen
      containers:
        - name: nginx
          image: nginx
          ports:
            - containerPort: 80
          env:
            - name: MYSQL_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: helen-secret
                  key: MYSQL_PASSWORD
            - name: SFTP_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: helen-secret
                  key: SFTP_PASSWORD


service.yaml

apiVersion: v1
kind: Service
metadata:
  name: nginx-service
  namespace: helen
spec:
  type: NodePort
  selector:
    app: nginx
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80
    nodePort: 30000  # 你也可以不指定,由系统自动分配

上面的文件依次apply后,即可将nginx服务启动,并通过宿主机ip:30000/进行访问nginx服务。这里的192.168.56.103是我虚拟机的ip

http://192.168.56.103:30000/
在这里插入图片描述

使用 ServiceAccount 模拟 kubectl 操作

🔧 步骤 1:获取该 ServiceAccount 的 Token

SECRET_NAME=$(kubectl get sa sa-helen -n helen -o jsonpath='{.secrets[0].name}')

kubectl get secret $SECRET_NAME -n helen -o jsonpath='{.data.token}' | base64 -d > /tmp/sa-helen.token

📜 步骤 2:获取当前集群的 CA 和 API Server 地址

# 获取 CA
kubectl get secret $SECRET_NAME -n helen -o jsonpath='{.data.ca\.crt}' | base64 -d > /tmp/ca.crt

# 获取 API Server 地址
APISERVER=$(kubectl config view --minify -o jsonpath='{.clusters[0].cluster.server}')

🧪 步骤 3:生成一个 kubeconfig 文件

cat <<EOF > /tmp/kubeconfig-sa-helen
apiVersion: v1
kind: Config
clusters:
- cluster:
    certificate-authority: /tmp/ca.crt
    server: ${APISERVER}
  name: kind-cluster
contexts:
- context:
    cluster: kind-cluster
    user: sa-helen
    namespace: helen
  name: sa-helen-context
current-context: sa-helen-context
users:
- name: sa-helen
  user:
    token: $(cat /tmp/sa-helen.token)
EOF

✅ 步骤 4:使用这个 kubeconfig 来运行 kubectl

KUBECONFIG=/tmp/kubeconfig-sa-helen kubectl get pods
KUBECONFIG=/tmp/kubeconfig-sa-helen kubectl get secrets

或者

export KUBECONFIG=/tmp/kubeconfig-sa-helen

如果role-helen 中没有对某资源的权限授权,这时候命令会失败,提示 forbidden。

<think>嗯,用户想在Kubernetes部署Nginx服务,我需要提供一个详细的指南。首先,我得回忆一下Kubernetes的基本概念,比如Deployment、Service这些资源类型。用户可能刚接触k8s,所以步骤需要清晰,从准备配置文件开始。 用户提供的引用里提到了Deployment和Service的配置,还有查看Pod状态的命令。我应该按照创建Deployment、暴露Service、验证状态的顺序来组织步骤。注意要确保YAML文件的正确性,比如apiVersion和selector的匹配。 可能用户还需要知道如何访问部署好的Nginx,所以需要解释Service的类型,比如NodePort或者LoadBalancer。引用中有一个例子用了NodePort,端口是30080,这个可以作为示例。同时,要提醒用户根据实际环境调整,比如云环境可能用LoadBalancer。 验证部分,检查Pod、Deployment、Service的状态是关键。引用中的kubectl命令可以直接参考,比如kubectl get pods -n web,但可能需要说明命名空间是否要创建,或者默认使用default。 用户可能遇到的问题,比如镜像拉取失败、端口冲突,或者标签不匹配导致Service无法找到Pod。应该在注意事项里提到这些,帮助用户排查常见问题。 另外,用户可能需要扩展应用,比如调整副本数,可以用kubectl scale命令,这部分在优化或调整部署时有用,也应该包含进去。 最后,生成的相关问题要考虑用户后续可能的需求,比如如何配置Ingress或者持久化存储,这些是进阶使用,但可以作为相关问题引导用户深入学习。</think>### 分步指南:在 Kubernetes部署 Nginx 服务 #### 一、创建 Deployment 配置文件 1. 编写 `nginx-deployment.yaml` 文件: ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: nginx-deployment spec: replicas: 3 # 设置副本数量 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:latest ports: - containerPort: 80 ``` 2. 执行部署命令: ```bash kubectl apply -f nginx-deployment.yaml ``` 该操作会创建包含3个Nginx实例的Pod集群,通过Deployment控制器保证副本数量[^3]。 #### 二、创建 Service 暴露服务 1. 编写 `nginx-service.yaml` 文件: ```yaml apiVersion: v1 kind: Service metadata: name: nginx-service spec: selector: app: nginx ports: - protocol: TCP port: 80 targetPort: 80 type: NodePort # 或 LoadBalancer(云环境) ``` 2. 应用服务配置: ```bash kubectl apply -f nginx-service.yaml ``` 通过Service将Pod的80端口映射到集群节点的随机端口(默认范围30000-32767)[^2]。 #### 三、验证部署状态 1. 查看Pod运行状态: ```bash kubectl get pods -l app=nginx ``` 正常状态应显示: ``` NAME READY STATUS RESTARTS AGE nginx-deployment-5549666998-7b6xt 1/1 Running 0 5m nginx-deployment-5549666998-g6ncl 1/1 Running 0 5m nginx-deployment-5549666998-w5cdw 1/1 Running 0 5m ``` 2. 查看Service详细信息: ```bash kubectl get svc nginx-service ``` 输出示例: ``` NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE nginx-service NodePort 10.96.58.201 <none> 80:30080/TCP 2m ``` #### 四、访问服务 1. 通过NodePort访问: ```bash curl http://<节点IP>:30080 ``` 2. 或通过临时端口转发: ```bash kubectl port-forward service/nginx-service 8080:80 ``` 访问 http://localhost:8080 即可看到Nginx欢迎页 #### 五、扩展应用(可选) 调整副本数量: ```bash kubectl scale deployment nginx-deployment --replicas=5 ``` ### 注意事项 1. 镜像版本:建议指定稳定版本如 `nginx:1.25` 替代 `latest` 2. 网络策略:若集群启用NetworkPolicy,需配置允许80端口流量 3. 资源配置:生产环境应添加resources限制: ```yaml resources: limits: memory: "256Mi" cpu: "500m" ``` ### 架构示意图 $$ \begin{array}{ccc} \text{Client} & \rightarrow & \text{NodePort (30080)} \\ & \downarrow & \\ \text{kube-proxy} & \rightsquigarrow & \text{Pod (80)} \\ & \downarrow & \\ \text{Service} & \leftrightsquigarrow & \text{Deployment} \\ \end{array} $$
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

RayCheungCode

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值