Maison > développement back-end > Golang > le corps du texte

DevOpsifier une application Web Go : un guide de bout en bout

WBOY
Libérer: 2024-09-06 06:39:02
original
685 Les gens l'ont consulté

介绍

在这篇文章中,我将指导您完成基于 Go 的 Web 应用程序的 DevOpsifying 过程。我们将涵盖从使用 Docker 将应用程序容器化到使用 Helm 将其部署在 Kubernetes 集群 (AWS EKS) 上、设置与 GitHub Actions 的持续集成以及使用 ArgoCD 自动化部署的所有内容。在本教程结束时,您将拥有一个完全可操作、支持 CI/CD 的 Go Web 应用程序。

先决条件

开始此项目之前,请确保您满足以下先决条件:

AWS 帐户:您需要一个有效的 AWS 帐户来创建和管理 EKS 集群,以部署基于 Go 的应用程序。

DockerHub 帐户: 您应该有一个 DockerHub 帐户来推送您的 Docker 镜像。

基本 DevOps 知识:熟悉 DevOps 概念和实践至关重要,包括了解 CI/CD 管道、容器化、编排和云部署。

Helm:打包和部署应用程序需要具备 Kubernetes 包管理器 Helm 的基本知识。

通过满足这些先决条件,您将做好充分准备按照本指南中的步骤进行操作,并成功对基于 Go 的应用程序进行 DevOpsify!

第 1 步:获取源代码

要开始该项目,您需要从 GitHub 存储库克隆源代码。使用以下命令克隆项目:

git clone https://github.com/iam-veeramalla/go-web-app-devops.git
Copier après la connexion

此存储库包含使用本指南中描述的 DevOps 实践设置和部署基于 Go 的应用程序所需的所有文件和配置。克隆后,您可以浏览以下步骤并按照这些步骤容器化、部署和管理应用程序。

第 2 步:容器化 Go Web 应用程序

第一步是容器化我们的 Go 应用程序。我们将使用多阶段 Dockerfile 来构建 Go 应用程序并创建轻量级的生产就绪映像。

FROM golang:1.22.5 as build

WORKDIR /app

COPY go.mod .

RUN go mod download

COPY . .

RUN go build -o main .

FROM gcr.io/distroless/base

WORKDIR /app

COPY --from=build /app/main .

COPY --from=build /app/static ./static

EXPOSE 8080

CMD ["./main"]
Copier après la connexion

构建和推送 Docker 镜像的命令:

docker login
docker build . -t go-web-app
docker push go-web-app:latest
Copier après la connexion

在此 Dockerfile 中,第一阶段使用 Golang 镜像来构建应用程序。第二阶段使用 distroless 基础镜像,它更小、更安全,仅包含运行 Go 应用程序所需的文件。

步骤 3:使用 AWS EKS 在 Kubernetes 上部署

接下来,我们将把容器化应用程序部署到 Kubernetes 集群。以下是如何设置集群和部署应用程序。

创建 EKS 集群:

eksctl create cluster --name demo-cluster --region us-east-1
Copier après la connexion

部署配置(deployment.yaml):

apiVersion: apps/v1
kind: Deployment
metadata:
  name: go-web-app
  labels:
    app: go-web-app
spec:
  replicas: 1
  selector:
    matchLabels:
      app: go-web-app
  template:
    metadata:
      labels:
        app: go-web-app
    spec:
      containers:
      - name: go-web-app
        image: iamamash/go-web-app:latest
        ports:
        - containerPort: 8080
Copier après la connexion

服务配置(service.yaml):

apiVersion: v1
kind: Service
metadata:
  name: go-web-app
  labels:
    app: go-web-app
spec:
  ports:
  - port: 80
    targetPort: 8080
    protocol: TCP
  selector:
    app: go-web-app
  type: ClusterIP
Copier après la connexion

入口配置(ingress.yaml):

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: go-web-app
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  ingressClassName: nginx
  rules:
  - host: go-web-app.local
    http:
      paths: 
      - path: /
        pathType: Prefix
        backend:
          service:
            name: go-web-app
            port:
              number: 80
Copier après la connexion

使用 kubectl 应用配置:

kubectl apply -f deployment.yaml
kubectl apply -f service.yaml
kubectl apply -f ingress.yaml

Copier après la connexion

设置 Nginx Ingress 控制器:

Kubernetes 中的入口控制器管理对集群内服务的外部访问,通常处理 HTTP 和 HTTPS 流量。它提供集中式路由,允许您定义流量如何到达您的服务的规则。在这个项目中,我们使用 Nginx Ingress 控制器来有效管理流量并将流量路由到部署在 Kubernetes 集群中的基于 Go 的应用程序。

kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.11.1/deploy/static/provider/aws/deploy.yaml
Copier après la connexion

第四步:用Helm打包

为了更有效地管理我们的 Kubernetes 资源,我们使用 Helm(Kubernetes 的包管理器)来打包我们的应用程序。

创建 Helm 图表:

helm create go-web-app-chart
Copier après la connexion

创建图表后,用您的deployment.yaml、service.yaml 和 ingress.yaml 文件替换 templates 目录中的所有内容。

更新values.yaml:values.yaml 文件将包含动态值,例如 Docker 镜像标签。该标签将根据 GitHub Actions 运行 ID 自动更新,确保每个部署都是唯一的。

# Default values for go-web-app-chart.
replicaCount: 1

image:
  repository: iamamash/Go-Web-App
  pullPolicy: IfNotPresent
  tag: "10620920515" # Will be updated by CI/CD pipeline

ingress:
  enabled: false
  className: ""
  annotations: {}
  hosts:
    - host: chart-example.local
      paths:
        - path: /
          pathType: ImplementationSpecific
Copier après la connexion

头盔部署:

kubectl delete -f k8s/.
helm install go-web-app helm/go-web-app-chart
kubectl get all
Copier après la connexion

第 5 步:与 GitHub Actions 持续集成

为了自动构建和部署我们的应用程序,我们使用 GitHub Actions 设置了 CI/CD 管道。

GitHub Actions 工作流程 (.github/workflows/cicd.yaml):

name: CI/CD

on:
  push:
    branches:
      - main
    paths-ignore:
      - 'helm/**'
      - 'README.md'

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - name: Checkout repository
      uses: actions/checkout@v4

    - name: Set up Go 1.22
      uses: actions/setup-go@v2
      with:
        go-version: 1.22

    - name: Build
      run: go build -o go-web-app

    - name: Test
      run: go test ./...

  push:
    runs-on: ubuntu-latest
    needs: build
    steps:
    - name: Checkout repository
      uses: actions/checkout@v4

    - name: Set up Docker Buildx
      uses: docker/setup-buildx-action@v1

    - name: Login to DockerHub
      uses: docker/login-action@v3
      with:
        username: ${{ secrets.DOCKERHUB_USERNAME }}
        password: ${{ secrets.DOCKERHUB_TOKEN }}

    - name: Build and Push action
      uses: docker/build-push-action@v6
      with:
        context: .
        file: ./Dockerfile
        push: true
        tags: ${{ secrets.DOCKERHUB_USERNAME }}/go-web-app:${{github.run_id}}

  update-newtag-in-helm-chart:
    runs-on: ubuntu-latest
    needs: push
    steps:
    - name: Checkout repository
      uses: actions/checkout@v4
      with:
        token: ${{ secrets.TOKEN }}

    - name: Update tag in Helm chart
      run: |
        sed -i 's/tag: .*/tag: "${{github.run_id}}"/' helm/go-web-app-chart/values.yaml

    - name: Commit and push changes
      run: |
        git config --global user.email "ansari2002ksp@gmail.com"
        git config --global user.name "Amash Ansari"
        git add helm/go-web-app-chart/values.yaml
        git commit -m "Updated tag in Helm chart"
        git push
Copier après la connexion

To securely store sensitive information like DockerHub credentials and Personal Access Tokens (PAT) in GitHub, you can use GitHub Secrets. To create a secret, navigate to your repository on GitHub, go to Settings > Secrets and variables > Actions > New repository secret. Here, you can add secrets like DOCKERHUB_USERNAME, DOCKERHUB_TOKEN, and TOKEN. Once added, these secrets can be accessed in your GitHub Actions workflows using ${{ secrets.SECRET_NAME }} syntax, ensuring that your sensitive data is securely managed during the CI/CD process.

Step 6: Continuous Deployment with ArgoCD

Finally, we implement continuous deployment using ArgoCD to automatically deploy the application whenever changes are pushed.

Install ArgoCD:

kubectl create namespace argocd
kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml
kubectl patch svc argocd-server -n argocd -p '{"spec": {"type": "LoadBalancer"}}'
kubectl get svc argocd-server -n argocd
Copier après la connexion

Setup ArgoCD Project: To access the ArgoCD UI after setting it up, you first need to determine the external IP of the node where ArgoCD is running. You can obtain this by running the command:

kubectl get nodes -o wide
Copier après la connexion

Next, get the port number at which the ArgoCD server is running using:

kubectl get svc argocd-server -n argocd
Copier après la connexion

Once you have the external IP and port number, you can access the ArgoCD UI by navigating to http://:. For example, if the external IP is 54.161.25.151 and the port number is 30498, the URL to access ArgoCD UI would be http://54.161.25.151:30498.

To log in to the ArgoCD UI for the first time, use the default username admin. The password can be retrieved from the ArgoCD secrets using:

kubectl edit secret argocd-initial-admin-secret -n argocd
Copier après la connexion

Copy the encoded password from the data.password field and decode it using base64:

echo <encoded-password> | base64 --decode
Copier après la connexion

For example, if the encoded password is kjasdfbSNLnlkaW==, decoding it with:

echo kjasdfbSNLnlkaW== | base64 --decode
Copier après la connexion

will provide the actual password. Be sure to exclude any trailing % symbol from the decoded output when using the password to log in.

Now, after accessing the ArgoCD UI, since both ArgoCD and the application are in the same cluster, you can create a project. To do this, click on the "New App" button and fill in the required fields, such as:

  • App Name: Provide a name for your application.
  • Sync Policy: Choose between manual or automatic synchronization.
  • Self-Heal: Enable this option if you want ArgoCD to automatically fix any drift.
  • Source Path: Enter the GitHub repository URL where your application code resides.
  • Helm Chart Path: Specify the path to the Helm chart within your repository.
  • Destination: Set the Cluster URL and namespace where you want the application deployed.
  • Helm Values: Select the appropriate values.yaml file for your Helm chart.

After filling in these details, click on "Create" and wait for ArgoCD to create the project. ArgoCD will pick up the Helm chart and deploy the application to the Kubernetes cluster for you. You can verify the deployment using:

kubectl get all
Copier après la connexion

That's all you need to do!

Conclusion

Congratulations! You have successfully DevOpsified your Go web application. This end-to-end guide covered containerizing your application with Docker, deploying it with Kubernetes and Helm, automating builds with GitHub Actions, and setting up continuous deployments with ArgoCD. You are now ready to manage your Go application with full CI/CD capabilities.

DevOpsifying a Go Web Application: An End-to-End Guide

Feel free to leave your comments and feedback below! Happy DevOpsifying!

Reference

For a detailed video guide on deploying Go applications on AWS EKS, check out this video.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:dev.to
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!