helm 实践 mysql_如何使用Helm在Kubernetes上部署Laravel 7和MySQL

helm 实践 mysql

The author selected the Diversity in Tech Fund to receive a donation as part of the Write for DOnations program.

作者选择了“技术多元化”基金来接受捐赠,这是Write for DOnations计划的一部分。

介绍 (Introduction)

Laravel is one of the most popular open-source PHP application frameworks today. It is commonly deployed with a MySQL database but can be configured to use a variety of backend data storage options. Laravel prides itself on taking advantage of many of PHP’s modern features and extensive package ecosystem.

Laravel是当今最受欢迎的开源PHP应用程序框架之一。 它通常与MySQL数据库一起部署,但可以配置为使用各种后端数据存储选项。 Laravel以利用PHP的许多现代功能和广泛的软件包生态系统而自豪。

Kubernetes is a container orchestration platform that can be hosted on DigitalOcean Kubernetes clusters to take much of the administration work out of setting up and running containers in production. Helm is a Kubernetes package manager that makes configuring and installing services and pods on Kubernetes easier.

Kubernetes是一个容器编排平台,可以托管在DigitalOcean Kubernetes群集上 ,以在生产中设置和运行容器方面节省很多管理工作。 Helm是一个Kubernetes软件包管理器,它使在Kubernetes上配置和安装服务和Pod更加容易。

In this guide, you will create a Laravel PHP application, build your app into a Docker image, and deploy that image to a DigitalOcean Kubernetes cluster using the LAMP Helm chart. Next, you’ll set up an Ingress Controller to add SSL and a custom domain name to your app. When completed, you will have a working Laravel application connected to a MySQL database that is running on a Kubernetes cluster.

在本指南中,您将创建一个Laravel PHP应用程序,将您的应用程序构建到Docker映像中,然后使用LAMP Helm图表将该映像部署到DigitalOcean Kubernetes集群。 接下来,您将设置一个Ingress Controller,以向您的应用添加SSL和自定义域名。 完成后,您将有一个可运行的Laravel应用程序连接到在Kubernetes集群上运行MySQL数据库。

先决条件 (Prerequisites)

步骤1 —创建一个新的Laravel应用程序 (Step 1 — Creating a New Laravel Application)

In this step, you’ll use Docker to create a new Laravel 7 application, but you should be able to go through the same process with an existing Laravel application that uses MySQL as the backing database. The new application you build will verify that Laravel is connected to the database and display the name of the database.

在这一步中,您将使用Docker创建一个新的Laravel 7应用程序,但是您应该能够与使用MySQL作为备份数据库的现有Laravel应用程序进行相同的过程。 您构建的新应用程序将验证Laravel是否已连接到数据库并显示数据库的名称。

First, move to your home directory and then create a new Laravel application using a composer Docker container:

首先,移至主目录,然后使用composer Docker容器创建一个新的Laravel应用程序:

  • cd ~

    光盘〜
  • docker run --rm -v $(pwd):/app composer create-project --prefer-dist laravel/laravel laravel-kubernetes

    泊坞窗运行--rm -v $ {pwd):/ app composer create-project --prefer-dist laravel / laravel laravel-kubernetes

Once the container is done and all the Composer packages have been installed, you should see a fresh installation of Laravel in your current directory called laravel-kubernetes/. Navigate to that folder:

完成容器并安装了所有Composer软件包后,您应该在当前目录laravel-kubernetes/看到全新的Laravel安装。 导航到该文件夹​​:

  • cd ~/laravel-kubernetes

    cd〜/ laravel-kubernetes

You’ll execute the rest of this tutorial’s commands from here.

您将从此处执行本教程的其余命令。

The purpose of this application is to test your database connection and display its name in your browser. In order to test the database connection, open up the ./resources/views/welcome.blade.php file in a text editor:

此应用程序的目的是测试数据库连接并在浏览器中显示其名称。 为了测试数据库连接,在文本编辑器中打开./resources/views/welcome.blade.php文件:

  • nano ./resources/views/welcome.blade.php

    纳米./resources/views/welcome.blade.php

Find the section <div class="links">...</div> and replace its contents with the following:

找到<div class="links">...</div> ,并将其内容替换为以下内容:

./resources/views/welcome.blade.php
./resources/views/welcome.blade.php
...
<div class="links">
   <strong>Database Connected: </strong>
    @php
        try {
            DB::connection()->getPDO();
            echo DB::connection()->getDatabaseName();
            } catch (\Exception $e) {
            echo 'None';
        }
    @endphp
</div>
...

Save and close the file.

保存并关闭文件。

That’s all the customization you’ll need to make to the default Laravel app for this tutorial. Once completed, this brief snippet of PHP will test your database connection and display the database’s name on the Laravel splash screen in your web browser.

这就是您需要对本教程的默认Laravel应用进行自定义的全部操作。 完成后,此简短PHP代码片段将测试您的数据库连接,并在Web浏览器的Laravel启动屏幕上显示数据库的名称。

In the next step, you’ll use Docker to build an image containing this Laravel application and Docker Compose to test that it runs locally and connects to a MySQL database.

在下一步中,您将使用Docker构建包含此Laravel应用程序的映像,并使用Docker Compose测试它在本地运行并连接到MySQL数据库。

第2步—容器化您的Laravel应用程序 (Step 2 — Containerizing Your Laravel Application)

Now that you have created a new Laravel application, you’ll need to build your code into a Docker image and then test the image with Docker Compose. While the goal of this tutorial is to deploy your application to a Kubernetes cluster, Docker Compose is a convenient way to test your Docker image and configuration locally before running it in the cloud. This fast feedback loop can be useful for making and testing small changes.

现在,您已经创建了一个新的Laravel应用程序,您需要将代码构建到Docker映像中,然后使用Docker Compose测试该映像。 尽管本教程的目标是将应用程序部署到Kubernetes集群,但是Docker Compose是在本地运行Docker映像和配置之前在云中运行它的便捷方法。 快速反馈循环对于进行和测试较小的更改很有用。

First, using nano or your preferred text editor, create a file in the root of your Laravel application called Dockerfile:

首先,使用nano或您喜欢的文本编辑器,在您的Laravel应用程序的根目录中创建一个名为Dockerfile

  • nano ./Dockerfile

    纳米./Dockerfile

Add the following content. Docker will use this file to build your code into an image:

添加以下内容。 Docker将使用此文件将您的代码构建为映像:

./Dockerfile
./Dockerfile
FROM php:7.4-apache

# Install packages
RUN apt-get update && apt-get install -y \
    git \
    zip \
    curl \
    sudo \
    unzip \
    libicu-dev \
    libbz2-dev \
    libpng-dev \
    libjpeg-dev \
    libmcrypt-dev \
    libreadline-dev \
    libfreetype6-dev \
    g++

# Apache configuration
ENV APACHE_DOCUMENT_ROOT=/var/www/html/public
RUN sed -ri -e 's!/var/www/html!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/sites-available/*.conf
RUN sed -ri -e 's!/var/www/!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/apache2.conf /etc/apache2/conf-available/*.conf
RUN a2enmod rewrite headers

# Common PHP Extensions
RUN docker-php-ext-install \
    bz2 \
    intl \
    iconv \
    bcmath \
    opcache \
    calendar \
    pdo_mysql

# Ensure PHP logs are captured by the container
ENV LOG_CHANNEL=stderr

# Set a volume mount point for your code
VOLUME /var/www/html

# Copy code and run composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
COPY . /var/www/tmp
RUN cd /var/www/tmp && composer install --no-dev

# Ensure the entrypoint file can be run
RUN chmod +x /var/www/tmp/docker-entrypoint.sh
ENTRYPOINT ["/var/www/tmp/docker-entrypoint.sh"]

# The default apache run command
CMD ["apache2-foreground"]

Save and close the file.

保存并关闭文件。

This Dockerfile starts with the PHP 7.4 Apache Docker Image found on Docker Hub, then installs several Linux packages that are commonly required by Laravel applications. Next, it creates Apache configuration files and enables header rewrites. The Dockerfile installs several common PHP extensions and adds an environment variable to ensure that Laravel’s logs are streamed to the container via stderr. This will allow you to see Laravel logs by tailing your Docker Compose or Kubernetes logs.

该Dockerfile始于Docker Hub上PHP 7.4 Apache Docker Image ,然后安装了Laravel应用程序通常需要的几个Linux软件包。 接下来,它将创建Apache配置文件并启用标头重写。 Dockerfile安装了几个常见PHP扩展,并添加了一个环境变量以确保Laravel的日志通过stderr流传输到容器。 这将允许您通过拖尾Docker Compose或Kubernetes日志来查看Laravel日志。

Finally, the Dockerfile copies all the code in your Laravel application to /var/www/tmp and installs the Composer dependencies. It then sets an ENTRYPOINT, but you’ll need to create that file, which we will do next.

最后,Dockerfile将Laravel应用程序中的所有代码复制到/var/www/tmp并安装Composer依赖项。 然后,它设置一个ENTRYPOINT ,但是您需要创建该文件,接下来我们将进行创建。

At the root directory of your project, create a new file called docker-entrypoint.sh. This file will run when your container is run locally or in the Kubernetes cluster, and it will copy your Laravel application code from the /var/www/tmp directory to /var/www/html where Apache will be able to serve it.

在项目的根目录下,创建一个名为docker-entrypoint.sh的新文件。 该文件将在您的容器在本地或Kubernetes集群中运行时运行,并将您的Laravel应用程序代码从/var/www/tmp目录复制到/var/www/html ,Apache可以在其中使用该文件。

  • nano ./docker-entrypoint.sh

    纳米./docker-entrypoint.sh

Now add the following script:

现在添加以下脚本:

./docker-entrypoint.sh
./docker-entrypoint.sh
#!/bin/bash

cp -R /var/www/tmp/. /var/www/html/
chown -R www-data:www-data /var/www/html

exec "$@"

The final line, exec "$@" instructs the shell to run whatever command was passed in as an input argument next. This is important because you want Docker to continue running the Apache run command (apache2-foreground) after this script executes. Save and close the file.

最后一行exec "$@"指示shell运行接下来作为输入参数传递的命令。 这很重要,因为您希望Docker在此脚本执行后继续运行 Apache run命令( apache2-foreground )。 保存并关闭文件。

Next, create a .dockerignore file in your app’s root directory. This file will ensure that when you build your Docker image it won’t become polluted with packages or environment files that shouldn’t be copied into it:

接下来,在应用程序的根目录中创建一个.dockerignore文件。 该文件将确保在构建Docker映像时,该映像不会被不应复制到其中的软件包或环境文件污染:

  • nano ./.dockerignore

    纳米./.dockerignore
./.dockerignore
./.dockerignore
.env
/vendor

Save and close the file.

保存并关闭文件。

The last file that you need to create before you can run your app locally using Docker Compose is a docker-compose.yml file. But during the configuration of this YAML file, you will need to enter the APP_KEY that Laravel generated during installation. Find this by opening and searching the ./.env file, or by running the following cat and grep commands:

使用Docker Compose在本地运行应用程序之前,需要创建的最后一个文件是docker-compose.yml文件。 但是在配置此YAML文件的过程中,需要输入Laravel在安装过程中生成的APP_KEY 。 通过打开并搜索./.env文件或通过运行以下catgrep命令./.env文件:

  • cat .env | grep ^APP_KEY

    cat .env | grep ^ APP_KEY

You will see an output like this:

您将看到类似以下的输出:


   
   
Output
APP_KEY=base64:0EHhVpgg ... UjGE=

Copy your key to your clipboard. Be sure to include the base64: prefix. Now create the docker-compose.yml file in your app’s root directory:

将密钥复制到剪贴板。 确保包括base64:前缀。 现在在应用程序的根目录中创建docker-compose.yml文件:

  • nano ./docker-compose.yml

    纳米./docker-compose.yml

Here we will include your Laravel application’s PHP image as well as a MySQL container to run your database. Add the following content:

在这里,我们将包含您的Laravel应用程序PHP映像以及一个用于运行数据库MySQL容器。 添加以下内容:

./docker-compose.yml
./docker-compose.yml
version: '3.5'
services:
  php:
    image: your_docker_hub_username/laravel-kubernetes:latest
    restart: always
    ports:
      - 8000:80
    environment:
      - APP_KEY="your_laravel_app_key"
      - APP_ENV=local
      - APP_DEBUG=true
      - DB_PORT=3306
      - DB_HOST=mysql
      - DB_DATABASE
      - DB_USERNAME
      - DB_PASSWORD
  mysql:
    image: mysql:5.7
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=${DB_ROOT_PASSWORD}
      - MYSQL_DATABASE=${DB_DATABASE}
      - MYSQL_USER=${DB_USERNAME}
      - MYSQL_PASSWORD=${DB_PASSWORD}

Use the APP_KEY variable that you copied to your clipboard for the your_laravel_app_key variable, and use your Docker Hub username for the your_docker_hub_username variable. Save and close the file.

使用APP_KEY变量您复制到剪贴板的your_laravel_app_key变量,并使用您的码头工人集线器的用户名的your_docker_hub_username变量。 保存并关闭文件。

You’ll create the first image locally using docker build. The second image is the official MySQL Docker image available on Docker Hub. Both require several environment variables, which you’ll include when you run the containers.

您将使用docker build在本地创建第一个映像。 第二个映像是Docker Hub上提供的官方MySQL Docker映像 。 两者都需要几个环境变量,运行容器时将包括这些变量。

In order to build the Docker image containing your Laravel application, run the following command. Make sure to replace your_docker_hub_username with your username or your team’s username at Docker Hub where this image will be stored:

为了构建包含您的Laravel应用程序的Docker映像,请运行以下命令。 确保在存储此映像的Docker Hub上用您的用户名或团队的用户名替换your_docker_hub_username

  • docker build -t your_docker_hub_username/laravel-kubernetes:latest .

    docker build -t your_docker_hub_username / laravel-kubernetes:latest。

Next, you can run the two containers with Docker Compose with the required database credentials:

接下来,您可以使用Docker Compose使用所需的数据库凭据来运行两个容器:

  • DB_ROOT_PASSWORD=rootpassword DB_DATABASE=local_db DB_USERNAME=admin DB_PASSWORD=password docker-compose up -d

    DB_ROOT_PASSWORD = rootpassword DB_DATABASE = local_db DB_USERNAME = admin DB_PASSWORD = password docker-compose up -d

The four environment variables used here (DB_ROOT_PASSWORD, DB_DATABASE, DB_USERNAME, DB_PASSWORD) can be modified if you’d like, but since you are only testing your application locally, you don’t have to worry about securing them yet.

如果愿意,可以修改此处使用的四个环境变量( DB_ROOT_PASSWORDDB_DATABASEDB_USERNAMEDB_PASSWORD ),但是由于您只是在本地测试应用程序,因此不必担心保护它们的安全。

It may take up to 30 seconds for your MySQL database to initialize and your containers to be ready. Once they are, you can view your Laravel application on your machine at localhost:8000.

MySQL数据库初始化和准备就绪容器可能最多需要30秒。 一旦完成,您就可以在localhost:8000上的机器上查看Laravel应用程序。

Your PHP application will connect to your MySQL database. After a successful connection, the text “Database Connected: local_db” will appear beneath the Laravel logo.

您PHP应用程序将连接到您MySQL数据库。 成功连接之后,文本“ Database Connected:local_db”将出现在Laravel徽标下方。

Now that you’ve tested your Docker image locally using Docker Compose, you can bring the containers down by running docker-compose down:

既然您已经使用Docker Compose在本地测试了Docker映像,则可以通过运行docker-compose down容器:

  • docker-compose down

    码头工人组成

In the next section, you’ll push your Docker image to Docker Hub so that your Helm chart can use it to deploy your application to your Kubernetes cluster.

在下一节中,您将Docker映像推送到Docker Hub,以便您的Helm图表可以使用它将您的应用程序部署到Kubernetes集群。

步骤3 —将您的Docker映像推送到Docker Hub (Step 3 — Pushing Your Docker Image to Docker Hub)

The LAMP Helm Chart that you’ll use to deploy your code to Kubernetes requires that your code be available in a container registry. While you can push your image to a private or self-hosted registry, for the purposes of this tutorial you’ll use a publicly available and free Docker registry on Docker Hub.

您将用于将代码部署到Kubernetes的LAMP Helm Chart要求您的代码在容器注册表中可用。 虽然可以将映像推送到私有或自托管注册表,但出于本教程的目的,您将在Docker Hub上使用可公开获得的免费Docker注册表。

Access your account on Docker Hub using your web browser and then create a new repository called laravel-kubernetes.

使用Web浏览器访问Docker Hub上的帐户,然后创建一个名为laravel-kubernetes的新存储库。

Next, if you haven’t connected to Docker Hub from your local machine, you’ll need to log into Docker Hub. You can do this through the command line:

接下来,如果您尚未从本地计算机连接到Docker Hub,则需要登录Docker Hub。 您可以通过命令行执行此操作:

  • docker login -u your_docker_hub_username

    docker登录-u your_docker_hub_username

Enter your login credentials when prompted. This typically only needs to be done once per machine as Docker will save your credentials to the ~/.docker/config.json in your home directory.

出现提示时输入您的登录凭据。 每台机器通常只需要执行一次,因为Docker会将您的凭据保存到主目录中的~/.docker/config.json中。

Finally, push your image to Docker Hub:

最后,将映像推送到Docker Hub:

  • docker push your_docker_hub_username/laravel-kubernetes:latest

    码头工人推your_docker_hub_username / laravel-kubernetes:latest

It may take a few minutes to upload your app depending on your connecti on speed, but once Docker is done, you’ll see a final digest hash and the size of your image in the terminal. It will look something like this:

根据您的连接速度,可能需要花费几分钟来上传您的应用程序,但是一旦完成Docker,您将在终端中看到最终的摘要哈希值和图像大小。 它看起来像这样:


   
   
Output
latest: digest: sha256:df4bdeda91484c8c26a989b13b8f27ab14d93ab2e676e3c396714cb3811c4086 size: 4918

Now that your Laravel application is containerized and you’ve pushed an image to Docker Hub, you can use the image in a Helm Chart or Kubernetes deployment. In the next step, you’ll set custom values based on the LAMP Helm Chart and deploy it to your DigitalOcean Kubernetes cluster.

既然您的Laravel应用程序已容器化,并且已将映像推送到Docker Hub,则可以在Helm Chart或Kubernetes部署中使用该映像。 在下一步中,您将基于LAMP Helm Chart设置自定义值,并将其部署到DigitalOcean Kubernetes集群。

步骤4 —使用LAMP Helm Chart配置和部署应用程序 (Step 4 — Configuring and Deploying the Application with the LAMP Helm Chart)

Helm provides a number of Charts to help you set up Kubernetes applications using preset combinations of tools. While you could write your own Kubernetes service files to accomplish a similar deployment, you’ll see in this section that using a Helm Chart will require much less configuration.

Helm提供了许多图表 ,可帮助您使用工具的预设组合来设置Kubernetes应用程序。 尽管您可以编写自己的Kubernetes服务文件来完成类似的部署,但在本节中您将看到,使用Helm Chart所需的配置要少得多。

First, you’ll need a directory to store all your Helm configuration files. Create a new directory in the root of your Laravel project called helm/:

首先,您需要一个目录来存储所有Helm配置文件。 在您的Laravel项目的根目录中创建一个名为helm/的新目录:

  • mkdir ./helm

    mkdir ./头盔

Inside the helm/ directory, you will create two new files: values.yml and secrets.yml. First create and open values.yml:

里面的helm/目录中,将创建两个新文件: values.ymlsecrets.yml 。 首先创建并打开values.yml

  • nano ./helm/values.yml

    纳米./helm/values.yml

The values.yml file will include non-secret configuration options that will override the default values in the LAMP Helm chart. Add the following configurations, making sure to replace your_docker_hub_username with your own username:

values.yml文件将包含values.yml配置选项,这些选项将覆盖LAMP Helm图表中的默认值。 添加以下配置,确保将your_docker_hub_username替换为您自己的用户名:

./helm/values.yml
./helm/values.yml
php:
  repository: "your_docker_hub_username/laravel-kubernetes"
  tag: "latest"
  fpmEnabled: false
  envVars:
    - name: APP_ENV
      value: production
    - name: APP_DEBUG
      value: false
    - name: DB_PORT
      value: 3306
    - name: DB_HOST
      value: localhost

Save and close the file.

保存并关闭文件。

Now create a secrets.yml file:

现在创建一个secrets.yml文件:

  • nano ./helm/secrets.yml

    纳米./helm/secrets.yml

secrets.yml will not be checked into version control. It will contain sensitive configuration information like your database password and Laravel app key. Add the following configurations, adjusting as needed to fit your credentials:

secrets.yml将不会检入版本控制。 它将包含敏感的配置信息,例如您的数据库密码和Laravel应用程序密钥。 添加以下配置,根据需要进行调整以适合您的凭据:

./helm/secrets.yml
./helm/secrets.yml
mysql:
  rootPassword: "your_database_root_password"
  user: your_database_user
  password: "your_database_password"
  database: your_database_name

php:
  envVars:
    - name: APP_KEY
      value: "your_laravel_app_key"
    - name: DB_DATABASE
      value: your_database_name
    - name: DB_USERNAME
      value: your_database_user
    - name: DB_PASSWORD
      value: "your_database_password"

Be sure to use strong username and password combinations for your production database, and use the same your_laravel_app_key as above, or open a new terminal window and generate a new one by running the following command. You can then copy the new value Laravel sets in your .env file:

确保对生产数据库使用强用户名和密码组合,并使用与上述相同的your_laravel_app_key ,或通过运行以下命令打开新的终端窗口并生成一个新的窗口。 然后,您可以将Laravel设置的新值复制到.env文件中:

  • docker run --rm -v $(pwd):/app php:cli php /app/artisan key:generate

    docker run --rm -v $ {pwd):/ app php:cli php / app / artisan键:生成

Save and close secrets.yml.

保存并关闭secrets.yml

Next, in order to prevent your secrets.yml file from being built into the Docker image or saved to version control, make sure to add the following line to both your .dockerignore and .gitignore files. Open and append /helm/secrets.yml to each file, or run the following command to add both:

接下来,为了防止将secrets.yml文件内置到Docker映像中或保存到版本控制中,请确保.dockerignore添加到.dockerignore.gitignore文件中。 打开/helm/secrets.yml并将其附加到每个文件,或运行以下命令以将两者都添加:

  • echo '/helm/secrets.yml' >> ./.dockerignore && echo '/helm/secrets.yml' >> ./.gitignore

    回声'/helm/secrets.yml'>> ./.dockerignore &&回声'/helm/secrets.yml'>> ./.gitignore

Now that you’ve created Helm configuration files for your application and the Docker image, you can install this Helm chart as a new release on your Kubernetes cluster. Install your chart from your application’s root directory:

现在,您已经为应用程序和Docker映像创建了Helm配置文件,您可以将此Kulm图表作为新版本安装在Kubernetes集群上。 从应用程序的根目录安装图表:

  • helm install laravel-kubernetes -f helm/values.yml -f helm/secrets.yml stable/lamp

    头盔安装laravel-kubernetes -f helm / values.yml -f helm / secrets.yml稳定/灯

You will see an output like this:

您将看到类似以下的输出:


   
   
Output
NAME: laravel-kubernetes LAST DEPLOYED: Mon May 18 13:21:20 2020 NAMESPACE: default STATUS: deployed REVISION: 1

Your application will take a minute or two to become available, but you can run this command to monitor the Kubernetes services in your cluster:

您的应用程序将需要一两分钟才能变得可用,但是您可以运行以下命令来监视集群中的Kubernetes服务:

  • kubectl get services -w

    kubectl获取服务-w

Look for the name of your application:

查找您的应用程序名称:


   
   
Output
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) laravel-kubernetes-lamp LoadBalancer your_cluster_ip your_external_ip 80:32175/TCP,3306:32243/TCP

When your new laravel-kubernetes-lamp service displays an IP address under EXTERNAL-IP, you can visit your_external_ip to see the application running on your Kubernetes cluster. Your app will connect to your database and you will see the name of the database below the Laravel logo, like you did when running your app locally on Docker Compose.

当新的laravel-kubernetes-lamp服务在EXTERNAL-IP下显示IP地址时,您可以访问your_external_ip来查看Kubernetes集群上正在运行的应用程序。 您的应用程序将连接到数据库,并且您会在Laravel徽标下方看到数据库名称,就像在Docker Compose上本地运行应用程序时一样。

Running a web application on an unsecured IP address might be okay for a proof of concept, but your website isn’t production-ready without an SSL certificate and a custom domain name. Before you set that up in the next step, uninstall your release via the command line:

对于概念验证,可以在不安全的IP地址上运行Web应用程序,但是如果没有SSL证书和自定义域名,您的网站就无法投入生产。 在下一步中进行设置之前,请通过命令行卸载发行版:

  • helm delete laravel-kubernetes

    删除laravel-kubernetes

In the next step you’ll expand on this first Helm configuration to add an Ingress controller, SSL certificate, and custom domain to your Laravel application.

在下一步中,您将扩展第一个Helm配置,以向您的Laravel应用程序添加一个Ingress控制器,SSL证书和自定义域。

步骤5 —将Ingress Controller和SSL添加到Kubernetes集群 (Step 5 — Adding an Ingress Controller and SSL to Your Kubernetes Cluster)

In Kubernetes, an Ingress Controller is responsible for exposing your application’s services to the internet. In the previous step, the LAMP Helm chart created a DigitalOcean Load Balancer and exposed your application directly via the load balancer’s IP address.

在Kubernetes中, 入口控制器负责将您的应用程序服务公开到Internet。 在上一步中,LAMP Helm图表创建了DigitalOcean负载均衡器,并直接通过负载均衡器的IP地址公开了您的应用程序。

You could terminate SSL and your domain name directly on the load balancer, but because you’re working in Kubernetes, it might be more convenient to manage it all in the same place. For much more about Ingress Controllers and details about the following steps, read How To Set Up an Nginx Ingress on DigitalOcean Kubernetes Using Helm.

您可以直接在负载均衡器上终止SSL和域名,但是由于您在Kubernetes中工作,因此在同一位置管理所有SSL可能会更方便。 有关Ingress Controller的更多信息以及以下步骤的详细信息,请阅读如何使用Helm在DigitalOcean Kubernetes上设置Nginx Ingress

The LAMP Helm chart includes a configuration option for supporting Ingress. Open up your helm/values.yml file:

LAMP Helm图表包含用于支持Ingress的配置选项。 打开您的helm/values.yml文件:

  • nano ./helm/values.yml

    纳米./helm/values.yml

Now add the following lines:

现在添加以下行:

./helm/values.yml
./helm/values.yml
...
# Use Ingress Controller
service:
  type: ClusterIP
  HTTPPort: 80
ingress:
  enabled: true
  domain: your_domain

This instructs your deployment not to install a load balancer and instead to expose the application to the Kubernetes cluster’s port 80 where the Ingress Controller will expose it to the internet. Save and close values.yml.

这指示您的部署不要安装负载均衡器,而是将应用程序公开给Kubernetes集群的端口80,入口控制器将在该端口上将其公开给Internet。 保存并关闭values.yml

Now run the helm install command you ran previously to get your Laravel application running again. Make sure to run the command from your app’s root directory:

现在运行您之前运行的helm install命令,以使您的Laravel应用程序再次运行。 确保从您应用的根目录运行命令:

  • helm install laravel-kubernetes -f helm/values.yml -f helm/secrets.yml stable/lamp

    头盔安装laravel-kubernetes -f helm / values.yml -f helm / secrets.yml稳定/灯

Next, install the nginx-ingress controller on your Kubernetes cluster using the Kubernetes-maintained Nginx Ingress Controller:

接下来,使用Kubernetes维护的Nginx Ingress Controller在您的Kubernetes集群上安装nginx-ingress 控制器

  • helm install nginx-ingress stable/nginx-ingress --set controller.publishService.enabled=true

    掌舵安装nginx-ingress stable / nginx-ingress --set controller.publishService.enabled = true

After installation, you will see an output like this:

安装后,您将看到类似以下的输出:


   
   
Output
NAME: nginx-ingress LAST DEPLOYED: Mon May 18 13:28:34 2020 NAMESPACE: default STATUS: deployed REVISION: 1

You also need an Ingress Resource to expose your Laravel app’s deployment. Create a new file in your app’s root directory called ingress.yml:

您还需要一个Ingress资源来公开您的Laravel应用程序的部署。 在应用程序的根目录中创建一个名为ingress.yml的新文件:

  • nano ./ingress.yml

    纳米./ingress.yml

This file defines your application’s host, SSL certificate manager, and backend service and port name. Add the following configurations, replaceing your_domain with the domain of your choice:

该文件定义您的应用程序的主机,SSL证书管理器以及后端服务和端口名称。 添加以下配置,将your_domain替换为您选择的域:

./ingress.yml
./ingress.yml
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: laravel-kubernetes-ingress
  annotations:
    kubernetes.io/ingress.class: nginx
    cert-manager.io/cluster-issuer: letsencrypt-prod
spec:
  tls:
    - hosts:
        - your_domain
      secretName: laravel-kubernetes-tls
  rules:
    - host: your_domain
      http:
        paths:
          - backend:
              serviceName: laravel-kubernetes-lamp
              servicePort: 80

Save and close the file.

保存并关闭文件。

Next, you should install Cert-Manager and create an issuer that will allow you to create production SSL certificates using Let’s Encrypt. Cert-Manager requires Custom Resource Definitions that you can apply from the Cert-Manager repository using the command line:

接下来,您应该安装Cert-Manager并创建一个颁发者,该颁发者将允许您使用Let's Encrypt创建生产SSL证书。 Cert-Manager需要自定义资源定义 ,您可以使用以下命令行从Cert-Manager存储库中应用它们:

  • kubectl apply --validate=false -f https://github.com/jetstack/cert-manager/releases/download/v0.15.0/cert-manager.crds.yaml

    kubectl apply --validate = false -f https://github.com/jetstack/cert-manager/releases/download/v0.15.0/cert-manager.crds.yaml

This will create a number of Kubernetes resources that will be displayed in the command line:

这将创建许多Kubernetes资源,这些资源将显示在命令行中:


   
   
Output
customresourcedefinition.apiextensions.k8s.io/certificaterequests.cert-manager.io created customresourcedefinition.apiextensions.k8s.io/certificates.cert-manager.io created customresourcedefinition.apiextensions.k8s.io/challenges.acme.cert-manager.io created customresourcedefinition.apiextensions.k8s.io/clusterissuers.cert-manager.io created customresourcedefinition.apiextensions.k8s.io/issuers.cert-manager.io created customresourcedefinition.apiextensions.k8s.io/orders.acme.cert-manager.io create

Cert-Manager also requires a namespace to isolate it in your Kubernetes cluster:

Cert-Manager还需要一个名称空间来将其隔离在Kubernetes集群中:

  • kubectl create namespace cert-manager

    kubectl创建名称空间cert-manager

You will see this output:

您将看到以下输出:


   
   
Output
namespace/cert-manager created

Because Jetstack’s Cert-Manager is not one of the Kubernetes-maintained charts, you will need to add the Jetstack Helm repository as well. Run the following command to make it available in Helm:

由于Jetstack的Cert-Manager不是Kubernetes维护的图表之一,因此您还需要添加Jetstack Helm存储库 。 运行以下命令以使其在Helm中可用:

  • helm repo add jetstack https://charts.jetstack.io

    头盔回购添加jetstack https://charts.jetstack.io

A successful addition will output the following:

成功添加将输出以下内容:


   
   
Output
"jetstack" has been added to your repositories

Now you’re ready to install Cert-Manager into the cert-manager namespace on your Kubernetes cluster:

现在,您可以将Cert-Manager安装到Kubernetes集群上的cert-manager命名空间中:

  • helm install cert-manager --version v0.15.0 --namespace cert-manager jetstack/cert-manager

    头盔安装证书管理器--version v0.15.0-命名空间证书管理器jetstack / cert-manager

When complete, you’ll see a summary of the deployment like this:

完成后,您将看到这样的部署摘要:


   
   
Output
NAME: cert-manager LAST DEPLOYED: Mon May 18 13:32:08 2020 NAMESPACE: cert-manager STATUS: deployed REVISION: 1

The last file you’ll need to add to your Laravel application’s root directory is a production_issuer.yml Kubernetes configuration file. Create the file:

您需要添加到Laravel应用程序根目录中的最后一个文件是production_issuer.yml Kubernetes配置文件。 创建文件:

  • nano ./production_issuer.yml

    纳米./production_issuer.yml

Now add the following:

现在添加以下内容:

apiVersion: cert-manager.io/v1alpha2
kind: ClusterIssuer
metadata:
  name: letsencrypt-prod
spec:
  acme:
    # Email address used for ACME registration
    email: your_email_address
    server: https://acme-v02.api.letsencrypt.org/directory
    privateKeySecretRef:
      # Name of a secret used to store the ACME account private key
      name: letsencrypt-prod-private-key
    # Add a single challenge solver, HTTP01 using nginx
    solvers:
      - http01:
          ingress:
            class: nginx

Save and close the file.

保存并关闭文件。

Let’s Encrypt will send your_email_address any important notices and expiration warnings, so be sure to add an address that you’ll check regularly. Save this file and create a new resource for both your Ingress resource and production issuer in your Kubernetes cluster:

让我们加密将向your_email_address发送任何重要的通知和到期警告,因此请确保添加一个您会定期检查的地址。 保存此文件并在Kubernetes集群中为Ingress资源和生产发行者创建新资源:

  • kubectl create -f ingress.yml

    kubectl创建-f ingress.yml
  • kubectl create -f production_issuer.yml

    kubectl创建-f production_issuer.yml

Finally, update your domain name’s DNS records to point an A record to your load balancer’s IP address. To find the IP address for your Ingress Controller enter:

最后,更新域名的DNS记录,以将A记录指向负载均衡器的IP地址。 要查找您的Ingress Controller的IP地址,请输入:

  • kubectl get service nginx-ingress-controller

    kubectl获取服务nginx-ingress-controller

   
   
Output
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE nginx-ingress-controller LoadBalancer your_cluster_ip your_external_ip 80:30187/TCP,443:31468/TCP 6m10s

Use the your_external_ip address as the IP address for your DNS A Record. The process for updating your DNS records varies depending on where you manage your domain names and DNS hosting, but if you’re using DigitalOcean you can reference our guide on How to Manage DNS Records.

使用your_external_ip地址作为DNS A记录的IP地址。 根据您在哪里管理域名和DNS托管,更新DNS记录的过程会有所不同,但是,如果您使用的是DigitalOcean,则可以参考我们有关如何管理DNS记录的指南。

Once your DNS records update and your SSL certificate is generated, your application will be available at your_domain and SSL will be enabled.

DNS记录更新并生成SSL证书后,您的应用程序将在your_domain可用,并且将启用SSL。

While your PHP application and database are already connected, you will still need to run database migrations. In the last step, you’ll see how to run Artisan commands on your Kubernetes pod to perform database migrations and other common maintenance tasks.

当您PHP应用程序和数据库已经连接时,您仍然需要运行数据库迁移。 在最后一步,您将看到如何在Kubernetes窗格上运行Artisan命令以执行数据库迁移和其他常见维护任务。

第6步-运行远程命令 (Step 6 — Running Remote Commands)

While your Laravel application is running and connected to the MySQL database in Kubernetes, there are several common operations that you should run on a new Laravel installation. One common task that you should perform is database migrations.

当您的Laravel应用程序正在运行并连接到Kubernetes中MySQL数据库时,应在新的Laravel安装上运行一些常见的操作。 您应该执行的一项常见任务是数据库迁移

Before you can run an Artisan command on your Laravel application, you need to know the name of the pod that is running your Laravel application container. Using the command line, you can view all the pods in your Kubernetes cluster:

之前,你可以在你的应用程序Laravel运行工匠命令,你需要知道的名字吊舱正在运行的应用程序Laravel容器。 使用命令行,您可以查看Kubernetes集群中的所有Pod:

  • kubectl get pods

    kubectl得到豆荚

You will see an output like this:

您将看到类似以下的输出:


   
   
Output
NAME READY STATUS RESTARTS AGE laravel-kubernetes-lamp-77fb989b46-wczgb 2/2 Running 0 16m

Select the pod for your laravel-kubernetes-lamp-... deployment. Make sure to use the name in your output and not the one listed above. Now you can run kubectl exec on it. For example, run a database migration using the artisan migrate command. You will add the --force flag because you’re running the pod in production:

选择用于laravel-kubernetes-lamp-...部署的容器。 确保在输出中使用该名称,而不要使用上面列出的名称。 现在您可以在其上运行kubectl exec 。 例如,使用artisan migrate命令运行数据库迁移。 您将添加--force标志,因为您正在生产中运行pod:

  • kubectl exec laravel-kubernetes-lamp-77fb989b46-wczgb -- php artisan migrate --force

    kubectl执行程序laravel-kubernetes-lamp-77fb989b46-wczgb -PHP Artisan Migration --force

This command will produce an output:

此命令将产生输出:


   
   
Output
Migration table created successfully. Migrating: 2014_10_12_000000_create_users_table Migrated: 2014_10_12_000000_create_users_table (0.16 seconds) Migrating: 2019_08_19_000000_create_failed_jobs_table Migrated: 2019_08_19_000000_create_failed_jobs_table (0.05 seconds)

You have now successfully deployed Laravel 7 and MySQL to Kubernetes and performed an essential database maintenance task.

您现在已经成功地将Laravel 7和MySQL部署到Kubernetes,并执行了基本的数据库维护任务。

结论 (Conclusion)

In this tutorial, you learned how to containerize a Laravel PHP application, connect it to a MySQL database, push a Docker image containing your code to Docker Hub, and then use a Helm chart to deploy that image to a DigitalOcean Kubernetes cluster. Finally, you added SSL and a custom domain name and learned how to run command line tools on your running pods.

在本教程中,您学习了如何将Laravel PHP应用程序容器化,将其连接到MySQL数据库,将包含代码的Docker映像推送到Docker Hub,然后使用Helm图表将该映像部署到DigitalOcean Kubernetes集群。 最后,您添加了SSL和自定义域名,并学习了如何在运行的Pod上运行命令行工具。

Kubernetes and Helm offer you a number of advantages over traditional LAMP stack hosting: scalability, the ability to swap out services without logging into your server directly, tools to perform rolling upgrades, and control over your hosting environment. That said, the complexity of initially containerizing and configuring your application makes the barrier to getting started quite high. With this guide as a starting point, deploying Laravel to Kubernetes becomes more attainable. From here you might consider learning more about the power of Laravel or adding monitoring tools to Kubernetes like Linkerd, which you can install manually with our guide or with a DigitalOcean 1-Click.

与传统的LAMP堆栈托管相比,Kubernetes和Helm为您提供了许多优势:可伸缩性,无需直接登录服务器即可交换服务的功能,执行滚动升级的工具以及对托管环境的控制。 就是说,最初对应用程序进行容器化和配置的复杂性使入门的障碍相当高。 以本指南为起点,将Laravel部署到Kubernetes变得更加可行。 在这里,您可能会考虑了解有关Laravel功能的更多信息,或向Kubernetes添加诸如Linkerd之类的监视工具,您可以通过我们的指南DigitalOcean 1-Click 手动安装

翻译自: https://www.digitalocean.com/community/tutorials/how-to-deploy-laravel-7-and-mysql-on-kubernetes-using-helm

helm 实践 mysql

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值