How to build a swoft development environment through Docker

不言
Release: 2023-04-03 12:42:02
Original
3058 people have browsed it

The content of this article is about how to build a swoft development environment through Docker. The content is very detailed. Friends in need can refer to it. I hope it can help you.

Swoft
The first new era PHP based on Swoole native coroutine High-performance coroutine full-stack component framework, built-in coroutine network server and commonly used coroutine clients, resident in memory, does not rely on traditional PHP-FPM, fully asynchronous non-blocking IO Implementation, using a writing method similar to that of a synchronous client to implement the use of an asynchronous client. There are no complex asynchronous callbacks, no cumbersome yields, and similar Go Language coroutines, flexible annotations, powerful global dependency injection containers, complete service governance, flexible and powerful AOP, and standard PSR Standard implementation, etc., can be used to build high-performance web systems, APIs, middleware, basic services, etc.

Preface

Swoftis ahigh-performance protocol built onSwooleCheng PHP full-stack framework, andSwooleis an advanced skill inPHPer, so it has also caused a lot of trouble to many people in the related environment installation,SwoftEven more so, this article will solve the deployment of running environment and development environment in an extremely simple way throughDocker.

Docker

As you can see from the encyclopedia,Dockeris an open source application container engine that allows developers to package Their applications and dependencies are packaged into a portable container, and then published to any popularLinuxmachine. Virtualization can also be achieved. The containers completely use the sandbox mechanism and will not interact with each other. Any interfacecan also be understood as we can package our code and running environment into a container. The packaged container can be published to any popularLinuxmachine, here refers to the Linux machine In fact, it is not accurate. Thanks to the development ofDocker for Windowsproject andHyper-V,Dockercan also run in good condition on Windows 10 system , but the author does not recommend usingDocker for Windowsin a production environment.

Docker noun concept

Here is a brief explanation and explanation of some commonly used nouns inDockerso that novices can understand the following

  • Dockerfile,Dockerfileis the description file ofDocker image, which is built through thedocker buildcommand Become amirror

  • Mirror (Image), built throughDockerfile, including operating system and operating environment

  • Container (Container), a container is a running image, which can be understood as the building and packaging stage in theDockerlife cycle, and The container is the

  • mirror warehouse (Repository) during the startup and execution phases, which is used to store the builtDocker imagewarehouse, understandable The installation process for installing Docker for a repository similar toGit

Dockeris not Complex, this section will introduce the installation process underLinuxandWindows 10systems, butis not recommendedonMacsystems. #Dockerenvironment to run or developSwoftprojects, because the performance of shared disks onMac for Dockeris extremely poor, which will causeSwoftto fail at startup The stage takes an extremely long time.

Install

DockeronLinuxwithdocker-compose

on

Linuxvia# The process of installingDockerusing ##yumandapt-getis quite simpleCentOS:yum install docker -y
Ubuntu:apt-get install docker-engine -y
You only need to execute the above line of commands in the terminal to complete the installation ofDocker
according to the difference of the system. After the installation is completed After that, we need to execute theservice docker startcommand to start theDockerservice.After installing

Docker

, we also need to installdocker-composeto facilitate subsequent use of DockerCentOS:yum install python -pip -y && pip install --upgrade pip && pip install -U docker-compose
Ubuntu:apt-get install python-pip -y && pip install --upgrade pip && pip install - U docker-compose
You only need to execute the above line of commands in the terminal according to the system differences to complete the installation ofdocker-compose
.

Installing Dockeranddocker-composeonWindows 10

We go directly to the Docker official website to download the corresponding installation package https:/ /store.docker.com/edit..., non-login users will seePlease Login to Download, which means we need to log in to the Docker account first before downloading. We directly click the button to go to the login page to complete. After registering or logging in, you can download it by clickingGet Dockeron the link page above. Note that we will also use this account later.
After downloading the installation package, you can directly run the installation package for installation. The whole process can be said to be fool-proof. Just continue to the next step. Note that you need to open the system'sHyper-Vbefore installation. The startup process is relatively simple. Please refer to other articles https://segmentfault.com/a/11... . Note thatHyper-Vconflicts withVMwareand the two cannot coexist. , you can only choose one. If you must use a virtual machine, such asVagrantand other tools, you can also run aLinux systemin the virtual machine, and then follow the instructions in this article The installation process ofLinux systemis processed, andDockeris run in the virtual machine as the development environment.
The latest version ofDockerinstallation package already containsdocker-compose, so there is no need to do extra operations.
After the installation is completed, restart the computer. When you see theLittle Whale (Docker Icon)on the taskbar showingDocker is running, it meansDockeris started. It worked.

How to build a swoft development environment through Docker

We need to right-clickDockerand clickSign in / Create Docker IDto log in to the one we just registeredDocker IDso that we can obtain public images from DockerHub.

Since we are using it for development, we also need to authorize the permissions of the shared directory. Right-clickDockerand clickSettingsto switch the settings interface toShared Drives, check thedisk drive letterwhere your project code is located, and clickApplyin the lower right corner to complete the authorization.

Swoft development environment

Modify the official defaultdocker-compose.ymlFile

We use the commandgit clone https://github.com/swoft-cloud/swofttoclone (clone) fromGithubSwoft project, and use thedocker-compose.ymlfile that comes with the project to implement an environment for development.docker-compose.ymlisdocker- For the orchestration configuration file of compose, let’s take a look at the contents of the official default file:

version: '3' services: swoft: container_name: swoft image: swoft/swoft ports: - "80:80" volumes: - ./:/var/www/swoft stdin_open: true tty: true command: php /var/www/swoft/bin/swoft start
Copy after login

This is a relatively simple orchestration file, with only one serviceswoftand no association with it. There is a lot of content. We will not explain too much about the file format ofdocker-compose.ymlhere. You can find the relevant content by yourself for reading and understanding.
A simple interpretation of the content of this file can be understood as using theswoft/swoftofficial image and setting the container name toswoft, binding80 in the containerPort and the80port of the host, set the./current directory and the/var/www/swoftdirectory in the container as a shared directory, enable Interactive terminal with the container and start theSwoftservice when starting the orchestration file.
We can notice that thecommandon the default orchestration file is configured withphp /var/www/swoft/bin/swoft start, which isStart the Swoft servicecommand, but if we onlyclone(clone)the project and executedocker-compose upto try to start thecontainer, we will get a failed result, Becausecomposer installhas not been executed to load the dependencies ofComposerand thevendorfolder andautoloadand other related files are missing, resulting in the inability to run correctlySwoftExample, let's look at the default orchestration file settingstdin_open: trueandtty: truetwo parameters, corresponding to thedockercommand respectively The simple understanding of the two parameters-iand-tis that-iturns on theinput(input)function,-topens ainteractive terminal (terminal)in a connection container. We can use these two parameters and change thecommandline of the arrangement file tocommand: /bin/bash, so that theSwoftservice is not started directly after the container is started, but we manually enter the container through theinteractive terminal (terminal)Go to boot.
The following is an example of a changeddocker-compose.ymlfile:

version: '3' services: swoft: container_name: swoft image: swoft/swoft ports: - "80:80" volumes: - ./:/var/www/swoft stdin_open: true tty: true command: /bin/bash
Copy after login

启动开发环境容器

此时我们在编排文件的所在目录启动一个终端(Shell), 然后执行docker-compose up -d-d的意思是以守护模式(Daemon Mode)运行,便于我们在同一个终端(Shell)进入到容器内,命令执行后我们可以看到Starting swoft ... done即表示启动容器成功。
如果在执行启动命令时得到一下错误,则说明宿主机的80端口已经被占用了,更改docker-compose.yml文件内的80:80为其它未被占用的端口即可,注意第一个80指的是宿主机的端口,第二个80指的是容器内的端口,也就是说我们只需要更改第一个即可

ERROR: for swoft Cannot start service swoft: b'driver failed programming external connectivity on endpoint swoft(dab0f4d00620e2f5c07e33084ca5cac6f08cb48018d6b737eadc035e5aa0b597): Bind for 0.0.0.0:80 failed: port is already allocated'
Copy after login

进入开发环境容器

通过执行docker ps命令可以查看启动的容器信息,下面为示例信息:

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES f22173763374 swoft/swoft:latest "docker-php-entrypoin" About a minute ago Up About a minute 0.0.0.0:80->80/tcp swoft
Copy after login

得知容器ID(Container ID)f22173763374容器名称(Container Name)swoft,我们可以执行docker exec -it f22173763374 bashdocker exec -it swoft bash通过交互式终端(terminal)进入到容器内。

如执行时报错the input device is not a TTY. If you are using mintty, try prefixing the command with 'winpty',可在docker exec命令前面增加winpty命令解决,即winpty docker exec -it swoft bash

运行以及开发调试

安装Composer依赖及生成自动加载(Autoload)文件

通过docker exec命令进入容器后,我们留意到光标左侧的内容变为root@f22173763374:即为已进入容器内,其中f22173763374为对应的容器ID(Container ID)
由于Swoft官方镜像swoft/swoft配置的工作目录为/var/www/swoft,而docker-compose.yml又将项目当前目录关联了容器/var/www/swoft目录,即通过docker exec进入的目录已经为/var/www/swoft目录,即项目目录,所以我们可以直接执行composer install命令来加载Composer的依赖并生成自动加载(Autoload)文件。
考虑到国内的网络环境,我们在执行composer install命令前可以先执行composer config -g repo.packagist composer https://packagist.phpcomposer.com命令配置Composer 中国镜像源加速安装速度。

启动Swoft服务

安装完Composer依赖后,便可以执行php bin/swoft start启动服务了,当你看到

root@f22173763374:/var/www/swoft# php bin/swoft start Server Information ******************************************************************** * HTTP | host: 0.0.0.0, port: 81, type: 1, worker: 1, mode: 3 * TCP | host: 0.0.0.0, port: 8099, type: 1, worker: 1 (Enabled) ******************************************************************** Server has been started. (master PID: 15, manager PID: 16) You can use CTRL + C to stop run.
Copy after login

即意味着你的Swoft以及启动成功了,我们可以打开浏览器访问一下http://127.0.0.1:80,当你看到下图即大功告成了!

How to build a swoft development environment through Docker

如果你绑定宿主机的端口不是80,则改成对应的即可;
如果访问看到的是Redis connection failure host=127.0.0.1 port=6379则说明缺少Redis服务,最简单直接的就是直接在当前容器内安装Redis Server,直接执行apt install -y redis-server && service redis-server start即可完成安装以及启动操作了;

Modify the code and make it effective

##SwoftThere will be a little difference between development inPHP-FPMmode, in ## In #PHP-FPMmode, directly change the code content, and then access the corresponding code to get the changed content. This is because inPHP-FPMmode, each request will reload the PHP code, andSwoftispersistently run, which means that after the service is started, the code does not need to be reloaded for accepted requests. Changes in this mode can makeSwoftOne of the reasons why a lot of code can be reused without the need to reload and re-instantiate is to greatly improve performance.Such a change will have a certain impact on development, which means that underSwoft
, you need torestart the Workerorrestart the serviceto make the changes The code takes effect, but thanks to thehot reloadfunction ofSwoft, code changes can be automatically checked and automaticallyrestarted the Worker, we only need to pass the project root directory Just change theAUTO_RELOADitem in the.envfile under totrue. If there is no.envfile in the project root directory, you can copy it directly..env.exampleThe file is.envand make corresponding changes. One thing to note is that only changing the code in theappdirectory will Beinghot reloadedfunction overloaded, changes to other codes will not be reloaded. This is because different codes are in different life cycles. Only code loaded afterWorkerStartcan Being overloaded, we will further explain this part when it comes to the life cycle ofSwoft.Related recommendations:

Configuring the scheduled task crontab in the Docker container (DaoCloud Docker Laravel5)


The above is the detailed content of How to build a swoft development environment through Docker. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!