如何在Ubuntu 20.04上使用Docker Compose安装和设置Laravel

介绍 (Introduction)

To containerize an application refers to the process of adapting an application and its components in order to be able to run it in lightweight environments known as containers. Such environments are isolated and disposable, and can be leveraged for developing, testing, and deploying applications to production.

容器化应用程序是指适应应用程序及其组件的过程,以便能够在称为容器的轻量级环境中运行它。 这样的环境是孤立且可抛弃的,可用于开发,测试和部署应用程序到生产环境。

In this guide, we’ll use Docker Compose to containerize a Laravel application for development. When you’re finished, you’ll have a demo Laravel application running on three separate service containers:

在本指南中,我们将使用Docker Compose容器化Laravel应用程序进行开发。 完成后,您将在三个独立的服务容器上运行一个演示Laravel应用程序:

  • An app service running PHP7.4-FPM;

    运行PHP7.4-FPM的app服务;

  • A db service running MySQL 5.7;

    运行MySQL 5.7的db服务;

  • An nginx service that uses the app service to parse PHP code before serving the Laravel application to the final user.

    一个nginx使用该服务app服务的服务应用Laravel到最终用户之前解析PHP代码。

To allow for a streamlined development process and facilitate application debugging, we’ll keep application files in sync by using shared volumes. We’ll also see how to use docker-compose exec commands to run Composer and Artisan on the app container.

为了简化开发过程并简化应用程序调试,我们将使用共享卷使应用程序文件同步。 我们还将看到如何使用docker-compose exec命令在app容器上运行ComposerArtisan

先决条件 (Prerequisites)

第1步-获取演示应用程序 (Step 1 — Obtaining the Demo Application)

To get started, we’ll fetch the demo Laravel application from its Github repository. We’re interested in the tutorial-01 branch, which contains the basic Laravel application we’ve created in the first guide of this series.

首先,我们将从其Github存储库中获取演示Laravel应用程序。 我们对tutorial-01分支感兴趣,该分支包含我们在本系列第一本指南中创建的基本Laravel应用程序。

To obtain the application code that is compatible with this tutorial, download release tutorial-1.0.1 to your home directory with:

要获取与本教程兼容的应用程序代码,请使用以下命令将版本tutorial-1.0.1下载到您的主目录:

  • cd ~

    光盘〜
  • curl -L https://github.com/do-community/travellist-laravel-demo/archive/tutorial-1.0.1.zip -o travellist.zip

    curl -L https://github.com/do-community/travellist-laravel-demo/archive/tutorial-1.0.1.zip -o travellist.zip

We’ll need the unzip command to unpack the application code. In case you haven’t installed this package before, do so now with:

我们需要unzip命令来解压缩应用程序代码。 如果您以前从未安装过此软件包,请立即执行以下操作:

  • sudo apt update

    sudo apt更新
  • sudo apt install unzip

    sudo apt安装解压缩

Now, unzip the contents of the application and rename the unpacked directory for easier access:

现在,解压缩应用程序的内容并重命名解压缩的目录,以便于访问:

  • unzip travellist.zip

    解压缩travellist.zip
  • mv travellist-laravel-demo-tutorial-1.0.1 travellist-demo

    mv travellist-laravel-demo-tutorial-1.0.1 travellist-demo

Navigate to the travellist-demo directory:

导航到travellist-demo目录:

  • cd travellist-demo

    cd travellist-demo

In the next step, we’ll create a .env configuration file to set up the application.

在下一步中,我们将创建一个.env配置文件来设置应用程序。

第2步-设置应用程序的.env文件 (Step 2 — Setting Up the Application’s .env File)

The Laravel configuration files are located in a directory called config, inside the application’s root directory. Additionally, a .env file is used to set up environment-dependent configuration, such as credentials and any information that might vary between deploys. This file is not included in revision control.

Laravel配置文件位于应用程序根目录内名为config的目录中。 此外, .env文件用于设置与环境相关的配置 ,例如凭据以及部署之间可能有所不同的任何信息。 此文件不包含在修订控制中。

Warning: The environment configuration file contains sensitive information about your server, including database credentials and security keys. For that reason, you should never share this file publicly.

警告 :环境配置文件包含有关服务器的敏感信息,包括数据库凭据和安全密钥。 因此,您永远不应公开共享此文件。

The values contained in the .env file will take precedence over the values set in regular configuration files located at the config directory. Each installation on a new environment requires a tailored environment file to define things such as database connection settings, debug options, application URL, among other items that may vary depending on which environment the application is running.

.env文件中包含的值将优先于位于config目录中的常规配置文件中设置的值。 在新环境中进行的每次安装都需要一个定制的环境文件来定义诸如数据库连接设置,调试选项,应用程序URL之类的内容,这些其他内容可能会根据应用程序运行的环境而有所不同。

We’ll now create a new .env file to customize the configuration options for the development environment we’re setting up. Laravel comes with an example.env file that we can copy to create our own:

现在,我们将创建一个新的.env文件,以针对要设置的开发环境自定义配置选项。 Laravel带有示例.env文件,我们可以复制.env文件以创建自己的文件:

  • cp .env.example .env

    cp .env.example .env

Open this file using nano or your text editor of choice:

使用nano或您选择的文本编辑器打开此文件:

  • nano .env

    纳米.env

The current .env file from the travellist demo application contains settings to use a local MySQL database, with 127.0.0.1 as database host. We need to update the DB_HOST variable so that it points to the database service we will create in our Docker environment. In this guide, we’ll call our database service db. Go ahead and replace the listed value of DB_HOST with the database service name:

travellist演示应用程序中的当前.env文件包含使用本地MySQL数据库(以127.0.0.1作为数据库主机)的设置。 我们需要更新DB_HOST变量,以便它指向我们将在Docker环境中创建的数据库服务。 在本指南中,我们将数据库服务称为db 。 继续,用数据库服务名称替换列出的DB_HOST值:

.env
.env
APP_NAME=Travellist
APP_ENV=dev
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost:8000

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=3306
DB_DATABASE=travellist
DB_USERNAME=travellist_user
DB_PASSWORD=password
...

Feel free to also change the database name, username, and password, if you wish. These variables will be leveraged in a later step where we’ll set up the docker-compose.yml file to configure our services.

如果需要,还可以随时更改数据库名称,用户名和密码。 这些变量将在以后的步骤中利用,我们将设置docker-compose.yml文件来配置我们的服务。

Save the file when you’re done editing. If you used nano, you can do that by pressing Ctrl+x, then Y and Enter to confirm.

完成编辑后,保存文件。 如果您使用nano ,则可以通过按Ctrl+x ,然后按Y并按Enter进行确认。

步骤3 —设置应用程序的Dockerfile (Step 3 — Setting Up the Application’s Dockerfile)

Although both our MySQL and Nginx services will be based on default images obtained from the Docker Hub, we still need to build a custom image for the application container. We’ll create a new Dockerfile for that.

尽管我们MySQL和Nginx服务都将基于从Docker Hub获得的默认映像,但是我们仍然需要为应用程序容器构建自定义映像。 我们将为此创建一个新的Dockerfile。

Our travellist image will be based on the php:7.4-fpm official PHP image from Docker Hub. On top of that basic PHP-FPM environment, we’ll install a few extra PHP modules and the Composer dependency management tool.

我们的旅行清单图像将基于Docker Hub的php:7.4-fpm 官方PHP图像 。 在基本PHP-FPM环境之上,我们将安装一些额外PHP模块和Composer依赖性管理工具。

We’ll also create a new system user; this is necessary to execute artisan and composer commands while developing the application. The uid setting ensures that the user inside the container has the same uid as your system user on your host machine, where you’re running Docker. This way, any files created by these commands are replicated in the host with the correct permissions. This also means that you’ll be able to use your code editor of choice in the host machine to develop the application that is running inside containers.

我们还将创建一个新的系统用户; 这是在开发应用程序时执行artisancomposer命令所必需的。 uid设置可确保容器内的用户具有与运行Docker的主机上的系统用户相同的uid。 这样,由这些命令创建的所有文件都将以正确的权限复制到主机中。 这也意味着您将能够在主机中使用所选的代码编辑器来开发在容器内运行的应用程序。

Create a new Dockerfile with:

使用以下命令创建一个新的Dockerfile:

  • nano Dockerfile

    纳米Dockerfile

Copy the following contents to your Dockerfile:

将以下内容复制到您的Dockerfile中:

Dockerfile
Docker文件
FROM php:7.4-fpm

# Arguments defined in docker-compose.yml
ARG user
ARG uid

# Install system dependencies
RUN apt-get update && apt-get install -y \
    git \
    curl \
    libpng-dev \
    libonig-dev \
    libxml2-dev \
    zip \
    unzip

# Clear cache
RUN apt-get clean && rm -rf /var/lib/apt/lists/*

# Install PHP extensions
RUN docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd

# Get latest Composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer

# Create system user to run Composer and Artisan Commands
RUN useradd -G www-data,root -u $uid -d /home/$user $user
RUN mkdir -p /home/$user/.composer && \
    chown -R $user:$user /home/$user

# Set working directory
WORKDIR /var/www

USER $user

Don’t forget to save the file when you’re done.

完成后,别忘了保存文件。

Our Dockerfile starts by defining the base image we’re using: php:7.4-fpm.

我们的Dockerfile首先定义了我们正在使用的基本映像: php:7.4-fpm

After installing system packages and PHP extensions, we install Composer by copying the composer executable from its latest official image to our own application image.

安装系统软件包和PHP扩展之后,我们通过将composer可执行文件从其最新的官方映像复制到我们自己的应用程序映像中来安装Composer。

A new system user is then created and set up using the user and uid arguments that were declared at the beginning of the Dockerfile. These values will be injected by Docker Compose at build time.

然后使用在Dockerfile开头声明的useruid参数创建并设置一个新的系统用户。 这些值将在构建时由Docker Compose注入。

Finally, we set the default working dir as /var/www and change to the newly created user. This will make sure you’re connecting as a regular user, and that you’re on the right directory, when running composer and artisan commands on the application container.

最后,我们将默认工作目录设置为/var/www并更改为新创建的用户。 当在应用程序容器上运行composerartisan命令时,这将确保您以常规用户身份连接,并且位于正确的目录中。

步骤4 —设置Nginx配置和数据库转储文件 (Step 4 — Setting Up Nginx Configuration and Database Dump Files)

When creating development environments with Docker Compose, it is often necessary to share configuration or initialization files with service containers, in order to set up or bootstrap those services. This practice facilitates making changes to configuration files to fine-tune your environment while you’re developing the application.

使用Docker Compose创建开发环境时,通常需要与服务容器共享配置或初始化文件,以便设置或引导这些服务。 这种做法有助于在开发应用程序时对配置文件进行更改以微调您的环境。

We’ll now set up a folder with files that will be used to configure and initialize our service containers.

现在,我们将建立一个包含文件的文件夹,该文件将用于配置和初始化我们的服务容器。

To set up Nginx, we’ll share a travellist.conf file that will configure how the application is served. Create the docker-compose/nginx folder with:

要设置Nginx,我们将共享一个travellist.conf文件,该文件将配置服务应用程序的方式。 使用以下命令创建docker-compose/nginx文件夹:

  • mkdir -p docker-compose/nginx

    mkdir -p docker-compose / nginx

Open a new file named travellist.conf within that directory:

在该目录中打开一个名为travellist.conf的新文件:

  • nano docker-compose/nginx/travellist.conf

    纳米docker-compose / nginx / travellist.conf

Copy the following Nginx configuration to that file:

将以下Nginx配置复制到该文件:

docker-compose/nginx/travellist.conf
docker-compose / nginx / travellist.conf
server {
    listen 80;
    index index.php index.html;
    error_log  /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
    root /var/www/public;
    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass app:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
    location / {
        try_files $uri $uri/ /index.php?$query_string;
        gzip_static on;
    }
}

This file will configure Nginx to listen on port 80 and use index.php as default index page. It will set the document root to /var/www/public, and then configure Nginx to use the app service on port 9000 to process *.php files.

该文件将Nginx配置为侦听端口80并使用index.php作为默认索引页面。 它将文档根目录设置为/var/www/public ,然后将Nginx配置为使用端口9000上的app服务来处理*.php文件。

Save and close the file when you’re done editing.

完成编辑后,保存并关闭文件。

To set up the MySQL database, we’ll share a database dump that will be imported when the container is initialized. This is a feature provided by the MySQL 5.7 image we’ll be using on that container.

要设置MySQL数据库,我们将共享一个数据库转储,该容器将在初始化容器时导入。 这是我们将在该容器上使用的MySQL 5.7映像所提供的功能。

Create a new folder for your MySQL initialization files inside the docker-compose folder:

docker-compose文件夹中为您MySQL初始化文件创建一个新文件夹:

  • mkdir docker-compose/mysql

    mkdir docker-compose / mysql

Open a new .sql file:

打开一个新的.sql文件:

  • nano docker-compose/mysql/init_db.sql

    纳米docker-compose / mysql / init_db.sql

The following MySQL dump is based on the database we’ve set up in our Laravel on LEMP guide. It will create a new table named places. Then, it will populate the table with a set of sample places.

以下MySQL转储基于我们在Laravel on LEMP指南中建立的数据库。 它将创建一个名为places的新表。 然后,它将使用一组示例位置填充表格。

Add the following code to the file:

将以下代码添加到文件中:

docker-compose/mysql/db_init.sql
docker-compose / mysql / db_init.sql
DROP TABLE IF EXISTS `places`;

CREATE TABLE `places` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `visited` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO `places` (name, visited) VALUES ('Berlin',0),('Budapest',0),('Cincinnati',1),('Denver',0),('Helsinki',0),('Lisbon',0),('Moscow',1),('Nairobi',0),('Oslo',1),('Rio',0),('Tokyo',0);

The places table contains three fields: id, name, and visited. The visited field is a flag used to identify the places that are still to go. Feel free to change the sample places or include new ones. Save and close the file when you’re done.

places表包含三个字段: idnamevisitedvisited域是用于标识仍要去的地方的标志。 随时更改示例位置或包括新位置。 完成后,保存并关闭文件。

We’ve finished setting up the application’s Dockerfile and the service configuration files. Next, we’ll set up Docker Compose to use these files when creating our services.

我们已经完成了设置应用程序的Dockerfile和服务配置文件。 接下来,我们将设置Docker Compose在创建服务时使用这些文件。

第5步—使用Docker Compose创建一个多容器环境 (Step 5 — Creating a Multi-Container Environment with Docker Compose)

Docker Compose enables you to create multi-container environments for applications running on Docker. It uses service definitions to build fully customizable environments with multiple containers that can share networks and data volumes. This allows for a seamless integration between application components.

Docker Compose使您能够为在Docker上运行的应用程序创建多容器环境。 它使用服务定义来构建具有多个可以共享网络和数据量的容器的完全可自定义的环境。 这允许在应用程序组件之间进行无缝集成。

To set up our service definitions, we’ll create a new file called docker-compose.yml. Typically, this file is located at the root of the application folder, and it defines your containerized environment, including the base images you will use to build your containers, and how your services will interact.

要设置服务定义,我们将创建一个名为docker-compose.yml的新文件。 通常,此文件位于应用程序文件夹的根目录下,它定义了容器化的环境,包括将用于构建容器的基本映像以及服务将如何交互。

We’ll define three different services in our docker-compose.yml file: app, db, and nginx.

我们将在docker-compose.yml文件中定义三种不同的服务: appdbnginx

The app service will build an image called travellist, based on the Dockerfile we’ve previously created. The container defined by this service will run a php-fpm server to parse PHP code and send the results back to the nginx service, which will be running on a separate container. The mysql service defines a container running a MySQL 5.7 server. Our services will share a bridge network named travellist.

app服务将基于我们先前创建的Dockerfile构建一个名为travellist的映像。 此服务定义的容器将运行php-fpm服务器以解析PHP代码并将结果发送回nginx服务,该服务将在单独的容器上运行。 mysql服务定义了一个运行MySQL 5.7服务器的容器。 我们的服务将共享一个名为travellist桥接网络

The application files will be synchronized on both the app and the nginx services via bind mounts. Bind mounts are useful in development environments because they allow for a performant two-way sync between host machine and containers.

应用程序文件将通过绑定安装appnginx服务上同步。 绑定安装在开发环境中很有用,因为它们允许主机和容器之间进行高性能的双向同步。

Create a new docker-compose.yml file at the root of the application folder:

在应用程序文件夹的根目录下创建一个新docker-compose.yml文件:

  • nano docker-compose.yml

    纳米docker-compose.yml

A typical docker-compose.yml file starts with a version definition, followed by a services node, under which all services are defined. Shared networks are usually defined at the bottom of that file.

典型docker-compose.yml文件以版本定义开头,后跟一个services节点,在该节点下定义了所有服务。 共享网络通常在该文件的底部定义。

To get started, copy this boilerplate code into your docker-compose.yml file:

首先,请将以下样板代码复制到您docker-compose.yml文件中:

docker-compose.yml
docker-compose.yml
version: "3.7"
services:


networks:
  travellist:
    driver: bridge

We’ll now edit the services node to include the app, db and nginx services.

现在,我们将编辑services节点以包括appdbnginx服务。

app服务 (The app Service)

The app service will set up a container named travellist-app. It builds a new Docker image based on a Dockerfile located in the same path as the docker-compose.yml file. The new image will be saved locally under the name travellist.

app服务将设置一个名为travellist-app的容器。 它基于与docker docker-compose.yml文件位于同一路径的Dockerfile构建新的Docker映像。 新图像将以travellist名称保存在本地。

Even though the document root being served as the application is located in the nginx container, we need the application files somewhere inside the app container as well, so we’re able to execute command line tasks with the Laravel Artisan tool.

即使用作应用程序的文档根目录位于nginx容器中,我们也需要在应用app容器内的某个位置放置app程序文件,因此我们能够使用Laravel Artisan工具执行命令行任务。

Copy the following service definition under your services node, inside the docker-compose.yml file:

将以下服务定义复制到services节点下docker-compose.yml文件中:

docker-compose.yml
docker-compose.yml
app:
    build:
      args:
        user: sammy
        uid: 1000
      context: ./
      dockerfile: Dockerfile
    image: travellist
    container_name: travellist-app
    restart: unless-stopped
    working_dir: /var/www/
    volumes:
      - ./:/var/www
    networks:
      - travellist

These settings do the following:

这些设置执行以下操作:

  • build: This configuration tells Docker Compose to build a local image for the app service, using the specified path (context) and Dockerfile for instructions. The arguments user and uid are injected into the Dockerfile to customize user creation commands at build time.

    build :此配置告诉Docker Compose使用指定的路径(上下文)和Dockerfile来为app服务构建本地映像。 将参数useruid注入到Dockerfile中,以在构建时自定义用户创建命令。

  • image: The name that will be used for the image being built.

    image :将用于构建image的名称。

  • container_name: Sets up the container name for this service.

    container_name :设置此服务的容器名称。

  • restart: Always restart, unless the service is stopped.

    restart :始终重新启动,除非服务已停止。

  • working_dir: Sets the default directory for this service as /var/www.

    working_dir :将此服务的默认目录设置为/var/www

  • volumes: Creates a shared volume that will synchronize contents from the current directory to /var/www inside the container. Notice that this is not your document root, since that will live in the nginx container.

    volumes :创建一个共享卷将从当前目录同步内容/var/www的容器的内部。 请注意,这不是您的文档根目录,因为它将位于nginx容器中。

  • networks: Sets up this service to use a network named travellist.

    networks :将此服务设置为使用名为travellist的网络。

db服务 (The db Service)

The db service uses a pre-built MySQL 5.7 image from Docker Hub. Because Docker Compose automatically loads .env variable files located in the same directory as the docker-compose.yml file, we can obtain our database settings from the Laravel .env file we created in a previous step.

db服务使用来自Docker Hub的预构建的MySQL 5.7映像 。 由于Docker Compose自动加载与.env docker-compose.yml文件位于同一目录中的.env变量文件,因此我们可以从上一步中创建的Laravel .env文件中获取数据库设置。

Include the following service definition in your services node, right after the app service:

app服务之后,在services节点中包括以下服务定义:

docker-compose.yml
docker-compose.yml
db:
    image: mysql:5.7
    container_name: travellist-db
    restart: unless-stopped
    environment:
      MYSQL_DATABASE: ${DB_DATABASE}
      MYSQL_ROOT_PASSWORD: ${DB_PASSWORD}
      MYSQL_PASSWORD: ${DB_PASSWORD}
      MYSQL_USER: ${DB_USERNAME}
      SERVICE_TAGS: dev
      SERVICE_NAME: mysql
    volumes:
      - ./docker-compose/mysql:/docker-entrypoint-initdb.d
    networks:
      - travellist

These settings do the following:

这些设置执行以下操作:

  • image: Defines the Docker image that should be used for this container. In this case, we’re using a MySQL 5.7 image from Docker Hub.

    image :定义该容器应使用的Docker映像。 在这种情况下,我们使用来自Docker HubMySQL 5.7映像。

  • container_name: Sets up the container name for this service: travellist-db.

    container_name :设置此服务的容器名称: travellist-db

  • restart: Always restart this service, unless it is explicitly stopped.

    restart :除非明确停止,否则始终重新启动此服务。

  • environment: Defines environment variables in the new container. We’re using values obtained from the Laravel .env file to set up our MySQL service, which will automatically create a new database and user based on the provided environment variables.

    environment :在新容器中定义环境变量。 我们使用从Laravel .env文件获得的值来设置我们MySQL服务,该服务将根据提供的环境变量自动创建新的数据库和用户。

  • volumes: Creates a volume to share a .sql database dump that will be used to initialize the application database. The MySQL image will automatically import .sql files placed in the /docker-entrypoint-initdb.d directory inside the container.

    volumes :创建卷共享.sql将用于初始化应用程序数据库数据库转储。 MySQL映像将自动导入放置在容器内/docker-entrypoint-initdb.d目录中的.sql文件。

  • networks: Sets up this service to use a network named travellist.

    networks :将此服务设置为使用名为travellist的网络。

nginx服务 (The nginx Service)

The nginx service uses a pre-built Nginx image on top of Alpine, a lightweight Linux distribution. It creates a container named travellist-nginx, and it uses the ports definition to create a redirection from port 8000 on the host system to port 80 inside the container.

nginx服务使用预建Nginx的图像之上的阿尔卑斯山 ,一个轻量级的Linux发行版。 它创建一个名为travellist-nginx的容器,并使用ports定义在主机系统上创建从主机端口8000到端口80的重定向。

Include the following service definition in your services node, right after the db service:

db服务之后的services节点中包括以下服务定义:

docker-compose.yml
docker-compose.yml
nginx:
    image: nginx:1.17-alpine
    container_name: travellist-nginx
    restart: unless-stopped
    ports:
      - 8000:80
    volumes:
      - ./:/var/www
      - ./docker-compose/nginx:/etc/nginx/conf.d
    networks:
      - travellist

These settings do the following:

这些设置执行以下操作:

  • image: Defines the Docker image that should be used for this container. In this case, we’re using the Alpine Nginx 1.17 image.

    image :定义该容器应使用的Docker映像。 在这种情况下,我们使用Alpine Nginx 1.17图像。

  • container_name: Sets up the container name for this service: travellist-nginx.

    container_name :为此服务设置容器名称: travellist-nginx

  • restart: Always restart this service, unless it is explicitly stopped.

    restart :除非明确停止,否则始终重新启动此服务。

  • ports: Sets up a port redirection that will allow external access via port 8000 to the web server running on port 80 inside the container.

    ports :设置端口重定向,该端口重定向将允许通过端口8000外部访问在容器内部的端口80上运行的Web服务器。

  • volumes: Creates two shared volumes. The first one will synchronize contents from the current directory to /var/www inside the container. This way, when you make local changes to the application files, they will be quickly reflected in the application being served by Nginx inside the container. The second volume will make sure our Nginx configuration file, located at docker-compose/nginx/travellist.conf, is copied to the container’s Nginx configuration folder.

    volumes :创建两个共享卷。 第一个将内容从当前目录同步到容器内的/var/www 。 这样,当您对应用程序文件进行本地更改时,它们将Swift反映在容器内Nginx服务的应用程序中。 第二卷将确保将位于docker-compose/nginx/travellist.conf的Nginx配置文件复制到容器的Nginx配置文件夹中。

  • networks: Sets up this service to use a network named travellist.

    networks :将此服务设置为使用名为travellist的网络。

完成docker-compose.yml文件 (Finished docker-compose.yml File)

This is how our finished docker-compose.yml file looks like:

这就是我们完成docker-compose.yml文件的样子:

docker-compose.yml
docker-compose.yml
version: "3.7"
services:
  app:
    build:
      args:
        user: sammy
        uid: 1000
      context: ./
      dockerfile: Dockerfile
    image: travellist
    container_name: travellist-app
    restart: unless-stopped
    working_dir: /var/www/
    volumes:
      - ./:/var/www
    networks:
      - travellist

  db:
    image: mysql:5.7
    container_name: travellist-db
    restart: unless-stopped
    environment:
      MYSQL_DATABASE: ${DB_DATABASE}
      MYSQL_ROOT_PASSWORD: ${DB_PASSWORD}
      MYSQL_PASSWORD: ${DB_PASSWORD}
      MYSQL_USER: ${DB_USERNAME}
      SERVICE_TAGS: dev
      SERVICE_NAME: mysql
    volumes:
      - ./docker-compose/mysql:/docker-entrypoint-initdb.d
    networks:
      - travellist

  nginx:
    image: nginx:alpine
    container_name: travellist-nginx
    restart: unless-stopped
    ports:
      - 8000:80
    volumes:
      - ./:/var/www
      - ./docker-compose/nginx:/etc/nginx/conf.d/
    networks:
      - travellist

networks:
  travellist:
    driver: bridge

Make sure you save the file when you’re done.

完成后,请确保保存文件。

第6步—使用Docker Compose运行应用程序 (Step 6 — Running the Application with Docker Compose)

We’ll now use docker-compose commands to build the application image and run the services we specified in our setup.

现在,我们将使用docker-compose命令构建应用程序映像并运行我们在设置中指定的服务。

Build the app image with the following command:

使用以下命令构建app映像:

  • docker-compose build app

    docker-compose构建应用

This command might take a few minutes to complete. You’ll see output similar to this:

此命令可能需要几分钟才能完成。 您将看到类似于以下的输出:


   
   
Output
Building app Step 1/11 : FROM php:7.4-fpm ---> fa37bd6db22a Step 2/11 : ARG user ---> Running in f71eb33b7459 Removing intermediate container f71eb33b7459 ---> 533c30216f34 Step 3/11 : ARG uid ---> Running in 60d2d2a84cda Removing intermediate container 60d2d2a84cda ---> 497fbf904605 Step 4/11 : RUN apt-get update && apt-get install -y git curl libpng-dev libonig-dev ... Step 7/11 : COPY --from=composer:latest /usr/bin/composer /usr/bin/composer ---> e499f74896e3 Step 8/11 : RUN useradd -G www-data,root -u $uid -d /home/$user $user ---> Running in 232ef9c7dbd1 Removing intermediate container 232ef9c7dbd1 ---> 870fa3220ffa Step 9/11 : RUN mkdir -p /home/$user/.composer && chown -R $user:$user /home/$user ---> Running in 7ca8c0cb7f09 Removing intermediate container 7ca8c0cb7f09 ---> 3d2ef9519a8e Step 10/11 : WORKDIR /var/www ---> Running in 4a964f91edfa Removing intermediate container 4a964f91edfa ---> 00ada639da21 Step 11/11 : USER $user ---> Running in 9f8e874fede9 Removing intermediate container 9f8e874fede9 ---> fe176ff4702b Successfully built fe176ff4702b Successfully tagged travellist:latest

When the build is finished, you can run the environment in background mode with:

构建完成后,可以使用以下命令在后台模式下运行环境:

  • docker-compose up -d

    docker-compose up -d

   
   
Output
Creating travellist-db ... done Creating travellist-app ... done Creating travellist-nginx ... done

This will run your containers in the background. To show information about the state of your active services, run:

这将在后台运行您的容器。 要显示有关活动服务状态的信息,请运行:

  • docker-compose ps

    码头工人组成ps

You’ll see output like this:

您将看到如下输出:


   
   
Output
Name Command State Ports -------------------------------------------------------------------------------- travellist-app docker-php-entrypoint php-fpm Up 9000/tcp travellist-db docker-entrypoint.sh mysqld Up 3306/tcp, 33060/tcp travellist-nginx /docker-entrypoint.sh ngin ... Up 0.0.0.0:8000->80/tcp

Your environment is now up and running, but we still need to execute a couple commands to finish setting up the application. You can use the docker-compose exec command to execute commands in the service containers, such as an ls -l to show detailed information about files in the application directory:

您的环境现已启动并正在运行,但是我们仍然需要执行几个命令来完成应用程序的设置。 您可以使用docker-compose exec命令在服务容器中执行命令,例如ls -l以显示有关应用程序目录中文件的详细信息:

  • docker-compose exec app ls -l

    docker-compose exec 应用 ls -l


   
   
Output
total 260 -rw-rw-r-- 1 sammy sammy 737 Jun 9 11:19 Dockerfile -rw-rw-r-- 1 sammy sammy 101 Jan 7 08:05 README.md drwxrwxr-x 6 sammy sammy 4096 Jan 7 08:05 app -rwxr-xr-x 1 sammy sammy 1686 Jan 7 08:05 artisan drwxrwxr-x 3 sammy sammy 4096 Jan 7 08:05 bootstrap -rw-rw-r-- 1 sammy sammy 1501 Jan 7 08:05 composer.json -rw-rw-r-- 1 sammy sammy 179071 Jan 7 08:05 composer.lock drwxrwxr-x 2 sammy sammy 4096 Jan 7 08:05 config drwxrwxr-x 5 sammy sammy 4096 Jan 7 08:05 database drwxrwxr-x 4 sammy sammy 4096 Jun 9 11:19 docker-compose -rw-rw-r-- 1 sammy sammy 965 Jun 9 11:27 docker-compose.yml -rw-rw-r-- 1 sammy sammy 1013 Jan 7 08:05 package.json -rw-rw-r-- 1 sammy sammy 1405 Jan 7 08:05 phpunit.xml drwxrwxr-x 2 sammy sammy 4096 Jan 7 08:05 public -rw-rw-r-- 1 sammy sammy 273 Jan 7 08:05 readme.md drwxrwxr-x 6 sammy sammy 4096 Jan 7 08:05 resources drwxrwxr-x 2 sammy sammy 4096 Jan 7 08:05 routes -rw-rw-r-- 1 sammy sammy 563 Jan 7 08:05 server.php drwxrwxr-x 5 sammy sammy 4096 Jan 7 08:05 storage drwxrwxr-x 4 sammy sammy 4096 Jan 7 08:05 tests drwxrwxr-x 41 sammy sammy 4096 Jun 9 11:32 vendor -rw-rw-r-- 1 sammy sammy 538 Jan 7 08:05 webpack.mix.js

We’ll now run composer install to install the application dependencies:

现在,我们将运行composer install来安装应用程序依赖项:

  • docker-compose exec app composer install

    docker-compose exec app composer安装

You’ll see output like this:

您将看到如下输出:


   
   
Output
Loading composer repositories with package information Installing dependencies (including require-dev) from lock file Package operations: 85 installs, 0 updates, 0 removals - Installing doctrine/inflector (1.3.1): Downloading (100%) - Installing doctrine/lexer (1.2.0): Downloading (100%) - Installing dragonmantank/cron-expression (v2.3.0): Downloading (100%) - Installing erusev/parsedown (1.7.4): Downloading (100%) - Installing symfony/polyfill-ctype (v1.13.1): Downloading (100%) - Installing phpoption/phpoption (1.7.2): Downloading (100%) - Installing vlucas/phpdotenv (v3.6.0): Downloading (100%) - Installing symfony/css-selector (v5.0.2): Downloading (100%) … Generating optimized autoload files > Illuminate\Foundation\ComposerScripts::postAutoloadDump > @php artisan package:discover --ansi Discovered Package: facade/ignition Discovered Package: fideloper/proxy Discovered Package: laravel/tinker Discovered Package: nesbot/carbon Discovered Package: nunomaduro/collision Package manifest generated successfully.

The last thing we need to do before testing the application is to generate a unique application key with the artisan Laravel command-line tool. This key is used to encrypt user sessions and other sensitive data:

我们需要测试应用程序之前做的最后一件事是产生了一个独特的应用关键artisan Laravel命令行工具。 此密钥用于加密用户会话和其他敏感数据:

  • docker-compose exec app php artisan key:generate

    docker-compose exec app php artisan key:generate


   
   
Output
Application key set successfully.

Now go to your browser and access your server’s domain name or IP address on port 8000:

现在转到浏览器并在端口8000上访问服务器的域名或IP地址:

http://server_domain_or_IP:8000

Note: In case you are running this demo on your local machine, use http://localhost:8000 to access the application from your browser.

注意 :如果要在本地计算机上运行此演示,请使用http://localhost:8000从浏览器访问该应用程序。

You’ll see a page like this:

您会看到这样的页面:

You can use the logs command to check the logs generated by your services:

您可以使用logs命令检查服务生成的日志:

  • docker-compose logs nginx

    docker-compose日志nginx

Attaching to travellist-nginx
…
travellist-nginx | /docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
travellist-nginx | /docker-entrypoint.sh: Configuration complete; ready for start up
travellist-nginx | 192.168.0.1 - - [09/Jun/2020:11:46:34 +0000] "GET / HTTP/1.1" 200 627 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"
travellist-nginx | 192.168.0.1 - - [09/Jun/2020:11:46:35 +0000] "GET / HTTP/1.1" 200 627 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"

If you want to pause your Docker Compose environment while keeping the state of all its services, run:

如果要在保持其所有服务状态的同时暂停Docker Compose环境,请运行:

  • docker-compose pause

    docker-compose暂停

   
   
Output
Pausing travellist-db ... done Pausing travellist-nginx ... done Pausing travellist-app ... done

You can then resume your services with:

然后,您可以通过以下方式恢复服务:

  • docker-compose unpause

    docker-compose取消暂停

   
   
Output
Unpausing travellist-app ... done Unpausing travellist-nginx ... done Unpausing travellist-db ... done

To shut down your Docker Compose environment and remove all of its containers, networks, and volumes, run:

要关闭Docker Compose环境并删除其所有容器,网络和卷,请运行:

  • docker-compose down

    码头工人组成

   
   
Output
Stopping travellist-nginx ... done Stopping travellist-db ... done Stopping travellist-app ... done Removing travellist-nginx ... done Removing travellist-db ... done Removing travellist-app ... done Removing network travellist-laravel-demo_travellist

For an overview of all Docker Compose commands, please check the Docker Compose command-line reference.

有关所有Docker Compose命令的概述,请查看Docker Compose命令行参考

结论 (Conclusion)

In this guide, we’ve set up a Docker environment with three containers using Docker Compose to define our infrastructure in a YAML file.

在本指南中,我们使用Docker Compose建立了具有三个容器的Docker环境,以在YAML文件中定义我们的基础架构。

From this point on, you can work on your Laravel application without needing to install and set up a local web server for development and testing. Moreover, you’ll be working with a disposable environment that can be easily replicated and distributed, which can be helpful while developing your application and also when moving towards a production environment.

从现在开始,您可以在Laravel应用程序上工作,而无需安装和设置用于开发和测试的本地Web服务器。 此外,您将在一个易于复制和分发的一次性环境中工作,这在开发应用程序以及向生产环境过渡时会很有帮助。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-install-and-set-up-laravel-with-docker-compose-on-ubuntu-20-04

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值