【问题标题】:How to CI/CD deploy static Dockerized React build files to S3如何 CI/CD 将静态 Dockerized React 构建文件部署到 S3
【发布时间】:2022-12-04 05:30:22
【问题描述】:

我目前有一个 React 应用程序,我为其设置了 AWS CodePipeline,它执行以下操作。

  1. 检测 GitHub 存储库中的更改
  2. 使用 buildspec.yaml 文件构建“构建”文件(使用 CodeBuild)
  3. 将“构建”文件推送到 S3 存储桶

    S3 存储桶配置为向我的域提供静态文件。

    这个设置很棒,因为它很便宜,我不需要让 EC2 服务器始终启动并运行来为这些静态文件提供服务,这是完全没有必要的。

    然而,最近我将这个应用程序 Docker 化了,当我在不同的机器上处理它时,这对我来说太棒了。

    然而,既然它已经被 Dockerized 化了,那么让 docker 容器构建“构建”文件并将它们推送到 S3 存储桶似乎是一个更好的主意,以确保在我的机器上构建的文件与被推送的文件相同到 S3 桶。

    理想情况下,当我像现在这样推送到回购时,我希望这一切都自动化。

    我看过很多关于如何自动创建 docker 镜像的教程,这些镜像被推送到 AWS ECR,然后使用 ECS (Fargate) 来运行容器。然而对我来说,这与在 EC2 服务器上运行我的应用程序是一样的……为什么我要完成所有这些,然后让一个容器在服务器上持续运行?现在它只是一个ECS服务器......

    所以我要问的是,我如何创建一个自动化的 CI/CD 管道来使用 docker 容器构建静态文件,然后将它们推送到 S3,就像我目前拥有的那样?

    这是当前的 CodeBuild buildspec.yaml 文件以供参考

    version: 0.2
    
    phases:
      install:
        runtime-versions:
          nodejs: 12
    
        commands:
          # install yarn
          - npm install yarn
          # install dependencies
          - yarn
          # so that build commands work
          - yarn add eslint-config-react-app
    
      build:
        commands:
          # run build script
          - yarn build
    
    artifacts:
      # include all files required to run application
      # we include only the static build files
      files:
        - '**/*'
      base-directory: 'build'  
    

【问题讨论】:

    标签: amazon-web-services docker continuous-integration devops aws-codepipeline


    【解决方案1】:

    要自动化 Dockerized React 应用程序的构建过程,您可以使用当前设置的相同 AWS CodePipeline,但您需要对 CodeBuild 项目进行一些更改以使用 Docker 构建环境而不是默认环境。

    为此,您需要先为您的 React 应用程序创建一个 Dockerfile,该文件将用于为您的应用程序构建 Docker 镜像。此 Dockerfile 应包含构建应用程序所需的所有说明,例如将源代码复制到映像中并安装任何依赖项。

    创建 Dockerfile 后,您可以更新 buildspec.yaml 文件以使用 Docker 构建环境并指定要使用的 Dockerfile。更新后的 buildspec.yaml 文件可能如下所示:

    version: 0.2
    
    phases:
      install:
        runtime-version:
          docker: 19
    
        commands:
          # build the Docker image for the application
          - docker build -t my-react-app:latest -f Dockerfile .
    
    build:
      commands:
        # run the Docker container with the built image to build the static files
        - docker run my-react-app:latest yarn build
    
    artifacts:
      files:
        - '**/*'
      base-directory: 'build'
    

    在此示例中,构建阶段将使用 Dockerfile 中的说明为您的应用程序构建 Docker 映像,然后运行容器为您的 React 应用程序构建静态文件。

    更新 buildspec.yaml 文件后,您可以将更改提交到 GitHub 存储库,CodePipeline 将自动检测更改并使用 Docker 构建环境运行更新的构建过程。这将确保 Docker 容器构建的静态文件与推送到 S3 存储桶的静态文件相同。

    请务必注意,为了在 CodeBuild 中使用 Docker 构建环境,您需要使用包含 Docker 运行时的构建映像,例如 aws/codebuild/standard:4.0 映像。您可以指定要在 CodeBuild 项目设置中使用的构建映像。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-20
      • 1970-01-01
      • 2011-06-29
      • 2020-04-04
      • 1970-01-01
      • 2021-10-17
      相关资源
      最近更新 更多