翻译进度
19
分块数量
5
参与人数

使用 Docker 来构建完美的 Laravel 本地开发环境

这是一篇协同翻译的文章,你可以点击『我来翻译』按钮来参与翻译。


文章太长,不想看?

如果不想读下面的“长篇大论”想快速上手的话,可以直接进行如下步骤:
安装适合你操作系统版本的 Docker , 克隆 本项目, 将您的Laravel应用程序文件添加到src目录中,并从您刚刚克隆的根项目目录中运行如下命令:
docker-compose build && docker-compose up -d

简单介绍

在我们开始之前,你应该知道这篇文章着重讲述点不是如何学习Docker的基础完整教程,也不是有关工具集复杂性的说明。

相比使用Docker和docker-compose来配置本地开发环境,这套工具,简化了繁琐的流程——你不必在电脑上安装和配置LAMP工具集。

这或许会是最适合你开发Laravel应用的一套工具。

ShareMan 翻译于 1个月前

如果你还不知道Docker是什么,你可以根据下面的概述来了解一下(节选自opensource.com):

Docker 是一个被设计来用于基于“容器”轻松创建、部署和运行你的服务或应用的工具。 容器可以让开发者将项目和所需的类库(依赖)打包在一起,将它合并为一个完整的包。

你可以把Docker视为精简版的VM。

你也许会问,这样做有什么好处呢?如果您有多个运行不同版本的Linux,PHP或任何其他网络软件的生产服务器,则可以将这些变量复制到您的容器中,并且可以保证该应用程序将按预期的方式在生产服务器上正常运行。

如果您在本地计算机上有多个跨不同版本的Laravel项目,那一定要来尝试一下Docker,你可以为每个应用程序指定特定的Docker配置,而不用像PHP切换版本那样要去修改实际的系统的环境变量。您甚至可以同时访问两个项目,并且每个容器彼此独立运行,互不受环境变量的影响。

听起来激动吗? 让我们开始Docker之旅吧!

ShareMan 翻译于 1个月前

安装 Docker

在本文中, 屏幕截图和参考资料与 MacOS 用户相关。然而,安装和使用说明和在 Windows 上非常相似。

第一步,获取安装器: https://docs.docker.com/docker-for-mac/ins....

运行典型的安装步骤,完成后打开应用。首次打开时,你将会被要求通过操作系统密码验证授权给 Docker,然后您会在顶部状态栏中看到小鲸鱼图标。

seeker-x2y 翻译于 1个月前

项目结构

我一直在 Laravel + Docker 项目中,使用下面这种目录结构。你的目录结构不必完全像我一样,但是本文是在假设你的项目是按照这样的结构的。

my-project.com/
├── nginx/
│   └── default.conf
├── src/
│   └── (Laravel app files)
├── docker-compose.yml
└── Dockerfile

在接下来的两个部分,我将解释一下每个文件的作用,但是现在只要按照上面的结构创建对应的文件即可。另外,请添加(或创建)Laravel 项目文件到 src 文件夹。

sunrui318 翻译于 1个月前

Creating Our Stack

A great rule of thumb when using Docker is that each container should provide a single service. Since we’re creating a typical LEMP stack, that means we’ll need one for our web server (Nginx), PHP, and MySQL. While theoretically we could create individual containers for each of these services and then attempt to link them together, Docker has a beautiful built-in tool for this called docker-compose.

What we do is define the services that will be used, and at runtime Docker provisions each one as a container and wraps them all in a virtual network. This means that each service will be accessible from every container.

To get started, open up the docker-compose.yml file and add the following to the top of it:

docker-compose.yml screenshot beginning

Some quick explanations for what we just added:

  • Version: 3, the newest and most recommended version of the docker-compose engine
  • Networks: We’re just using one network, laravel, which we’re not adding any options to besides the name
  • Services: Where we’ll specify the images that’ll make up our stack

Adding Nginx

Directly under the services heading that we specified at the bottom of the docker-compose.yml file above, you’ll add in the following:

docker-compose.yml screenshot of nginx service

What we’re doing in the above is telling Docker that we want a container called nginx, built from the nginx:stable-alpine image (whose full source you can see here). We’re using alpine linux as the base OS because of its light and responsive footprint.

Next we’re naming the container nginx and exposing its :80 port as :8080 on our local machine. This port number is what we’ll eventually use to access our site, and you can adjust it to any non-reserved port number that you like.

For the web server’s volumes, we’re adding in the two following:

  • Our local /src folder is bound to the container’s /var/www path. Not unlike a symlink, anything we modify in /src will be available to the server under /var/www immediately.
  • The /nginx/default.conf file we created is linked to the /etc/nginx/conf.d/default.conf container file, and will give us the ability to modify the nginx web server on our local machine.

You could specify any number of directories or files under this heading to symlink them from your local machine to the nginx container.

By adding both php and mysql (services we’ll create next) under the depends_on item, we’re telling Docker that on initialization the php and mysql containers need to be running before nginx does. Additionally, if we tried to spin up just the nginx container, it would also boot up both of those dependent containers.

Lastly, we’re specifying that this container is explicitly under the laravel network we created at the beginning of our docker-compose.yml file.

Adding MySQL

The next service we’re adding to our docker-compose.yml file is MySQL. This one is relatively straight-forward.

docker-compose.yml screenshot adding the mysql service

Initially we’re specifying the image and container name, as well as setting some miscellaneous settings that I feel have helped maintain MySQL’s stability in the container.

The default MySQL port of :3306 is the one we’re exposing to our local machine, and then using the environment object we can set a few variables used during initialization to modify the database created. Since we’re configuring Docker for a Laravel app, I’m using the default database name/username/password found in the typical Laravel .env file.

Just like with nginx, we’re attaching this service to the laravel network.\
✨ Simple!

Adding PHP

Unlike Nginx and MySQL, adding our PHP container is going to take a different, and slightly more complicated path. With the previous two services we were able to directly reference an image to build our container off of, however because of a dependency that Laravel requires we’re going to actually be building our own image off of a local Dockerfile.

Before we get to that part, add the following as the next (and last) service to our docker-compose.yml file.

docker-compose.yml screenshot of adding the php service

You can already spot the difference, we’re replacing the image heading we used before with a build one. Under it, we’re specifying the context as the current project directory and the dockerfile as Dockerfile (which we’ve already created earlier).

Like with our nginx container we’re specifying the same volume for the root directory, then exposing port :9000 for the container and setting the network to laravel.

Now that we have that service added, it’s time to add the following to our Dockerfile:

Dockerfile screenshot for building the PHP image

Yep, that’s it.

All we’re doing here is:

  • Specifying that we want our php container to be built from the 7.2-fpm-alpine PHP image.
  • Installing the pdo and pdo_mysql PHP extensions that Laravel’s ORM uses with its database methods.

The docker-php-ext-install command is built-in (and not well documented) in Docker. You can pass through any PHP extension and it will handle the installation and configuration within our newly-created container.

Configuring nginx

Remember our /nginx/default.conf file that we created? Open it up and add the following:

Screenshot of the default nginx configuration

There honestly isn’t much to discuss here, as it’s mostly a boilerplate nginx configuration used with most basic Laravel apps. Note that the root path was set to the public folder of our /var/www nginx directory that we linked our Laravel app to.

Starting Docker

We have all of our individual pieces in order, now it’s finally time to assemble our Docker network! Open up a terminal window and navigate to the root directory of this project. Since one of our containers (php) is using a Dockerfile as its image, and this is the first time we’re spinning up these containers, the first thing we need to do is run the build command to generate the image data:

docker-compose build

This will take a little while to finish up, and might seem like nothing’s happening for a while. Give it about 1–2 minutes and you should have seen Successfully built and Successfully tagged messages in your terminal. You can then proceed with actually starting up the containers using:

docker-compose up -d

Docker will create our laravel network and then create the three containers we’ve specified in the services section of our docker-compose.yml file. If you’re curious about the -d flag, it stands for detached and keeps the containers running after all of their commands have processed. Otherwise, Docker would stop them as soon as they’ve finished their initialization. Pretty pointless for a web server!

Configuring Laravel

Before we access our app for the first time, we need to make some small adjustments to our Laravel .env file. Specifically regarding the database connection and the app domain. Open up your project’s .env file in the src directory and modify the following lines:

  • DB_HOST=mysql - This name comes from the MySQL service we created in the docker-compose.yml file, and is used in the Docker network to reference the service from other containers.
  • APP_URL=http://localhost:8080 -  Add in the port number you’ve exposed in our nginx container to keep this pointing at a resolvable address.

Accessing Your App

Assuming everything in the above step started successfully, we can now visit our container with the exposed port and see our app’s landing page!

In your browser, navigate to http://localhost:8080 where 8080 is the first port that you specified under the nginx service in your docker-compose.yml file.

Screenshot of a browser showing the Laravel landing screen

💥 Boom! We have our Laravel app running in a Docker network!

Of course if you’ll probably also want to access your MySQL database using a tool like TablePlus, and getting connected to that is just as simple. All you’re going to do is use 127.0.0.1 as the host, along with the port you’ve exposed under the MySQL service in our docker-compose.yml file (which for this example we’ve kept as the default 3306).

Our username and password we’ve specified in the environment variables as MYSQL_USER and MYSQL_PASSWORDhomestead and secret respectively.

Screenshot of TablePlus configuration

Note: If you’re planning on running multiple networks at once for different projects, you’ll have to specify different ports to expose on your local machine (e.g. 8080 for one, 8081 for another). Otherwise, you’ll be greeted with a port is already allocated error during the container initialization.

Running Commands

Laravel utilizes the command line fairly often for things like migrations, queues, and tests. Executing these on our Docker network is super easy using docker-compose’s exec command.

Instead of a VM where you ssh into the system and execute commands directly on the OS, Docker prefers that you pass commands through to the container(s) and then the output of those commands is echoed back to your terminal. For example, let’s run the default migrations that Laravel comes with by running the following command in our terminal at the project root:

docker-compose exec php php /var/www/artisan migrate

Let's break this down a little:

  • docker-compose exec tells Docker that we want to execute a command on our container network.
  • php the container name we want to execute the command on. Since we’re going to be executing a PHP command, it needs to be on the container PHP is running on.
  • php /var/www/artisan migrate the actual name of the command we’re running. We’re using an absolute path to artisan that’s symlinked through our local volume at ./src and running a standard Laravel migration.

Screenshot of a terminal after running a docker-compose migrate command

You should be presented with the migration output after running our command, and your database will now be populated with two tables!

Any number of commands can be run from our local terminal into the Docker containers of our choosing. Just be aware of the services installed and available in the container you want to execute the command on.

Hint: If you’re adamant about wanting to ssh directly into a container to execute commands, there is a pretty simple workaround. Running\
docker-compose exec {container_name} /bin/sh will open up a persistent connection to the container specified in the {container_name} argument.

End of the Line

Well, there we have it! We’ve installed Docker, set up and configured a docker-compose file to create a LEMP stack of three containers wrapped in a single network, have exposed ports on that network that let us access our app and database, and have even run cli commands through docker-compose’s exec method.

Moving forward, if you want to bring down the containers and network, it’s as simple as navigating to your project’s root folder and running\
docker-compose down. This will both bring down, and destroy, the containers and any associated non-volume data that was stored in them.

Docker has opened up a whole world of development possibilities for me when I’m juggling multiple projects spanning different Laravel versions. I can easily have one project running on a Docker network with a PHP container using 7.1, and if I wanted to see how my current project would perform in PHP 7.3 it’s as simple as changing a single character in my Dockerfile, re-building the container, and bringing the docker-compose network back up.

I won’t deny it, you’ll get no better local development performance than running your stack directly on your machine’s hardware. But the tradeoff of performance for versatility, ease of use, parallel environments, and customization, greatly outweighs that for me.

本文章首发在 LearnKu.com 网站上。

本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://dev.to/aschmelyun/the-beauty-of-...

译文地址:https://learnku.com/server/t/39850

本帖已被设为精华帖!
参与译者:5
讨论数量: 1

这些代码截图都是什么工具做的呢?

1个月前 评论

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!