Swoft Novice to Tutorial-Building a Development Environment through Docker

  php, swoft, swoole


This series of articles will be introduced from the usage level.SwoftThe use of the framework and business development, for junior high school levelPHPer

The first new era PHP high-performance synergetic full stack componentization framework based on Swoole native synergetic, built-in synergetic network server and common synergetic client, memory resident, does not rely on traditional PHP-FPM, fully asynchronous non-blocking IO implementation, realizes the use of asynchronous client in a manner similar to synchronous client, does not have complicated asynchronous callback, and does not have complicated yield. It has the coordination process similar to Go language, flexible annotation, powerful global dependency injection container, perfect service governance, flexible and powerful AOP, standard PSR specification implementation, etc. It can be used to build high-performance Web systems, API, middleware, basic services, etc.


SwoftIt’s a place whereSwooleA built on top ofHigh Performance Concorde PHP Full Stack Framework, andSwooleInPHPerIt is an advanced skill, so it has also caused a lot of trouble to many people in the installation of related environment.SwoftEven more so, this article will passDockerThe deployment of the operating environment and development environment is solved in an extremely simple way.


As can be seen from the encyclopedia,Docker 是一个开源的的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的Linux机器上,也可以实现虚拟化,容器是完全使用沙箱机制,相互之间不会有任何接口, it can also be understood that we can package our code and running environment into a container, and the packaged container can be published to any popularLinuxOn the machine, the Linux machine referred to here is actually not accurate, thanks toDocker for WindowsProjects andHyper-VThe development of,DockerIt can also run on Windows 10 system in a good state, but the author does not recommend toDocker for WindowsUsed in production environment.

Docker noun concept

Right hereDockerSome commonly used nouns are simply explained and explained so that beginners can understand the following

  • Dockerfile,DockerfileYesDocker mirrorThe description of the file, throughdocker buildCommand to build intomirror image
  • Mirror imageImage), throughDockerfileBuilt, including operating system and operating environment
  • Container (Container), the container is a running mirror, can be understood as a mirror isDockerThe construction and packaging phase in the life cycle, while the container is the startup and execution phase.
  • Mirror warehouse (Repository), used to store the builtDocker mirrorThe warehouse, can be understood as similar toGitThe warehouse of

Install doc

DockerThe installation process of is not complicated, which will be described in this section.LinuxAndWindows 10The installation process under the system, andMacOn the system andNot recommendedUseDockerEnvironment to run or developSwoftProject, because inMac for DockerThe performance of shared disks on is extremely poor, resulting inSwoftThe start-up phase takes a long time.

InLinuxUpper installationDockerAnddocker-compose

InLinuxPass onyumAndapt-getTo installDockerThe process is quite simple
CentOS:yum install docker -y
Ubuntu:apt-get install docker-engine -y
According to the difference of the system, the above command can be executed at the terminal.DockerAfter the installation of, we need to perform itservice docker startCommand to start itDockerServices.

After installationDockerAfter that, we still need to install itdocker-composeSo as to facilitate the subsequent use of Docker.
CentOS: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
According to the difference of the system, the above command can be executed at the terminal.docker-composeThe installation of.

InWindows 10Upper installationDockerAnddocker-compose

We will go directly toDocker.comDownload the corresponding installation packagehttps://store.docker.com/edit …, non-login users we will seePlease Login to Download, which means that we should log in to the Docker account before downloading. We can click the button directly to the login page to complete the account registration or login and click on the link page above.Get DockerDownload, note that this account will be used later when we use it.
After downloading the installation package, the installation package can be directly run for installation. The whole process can be said to be silly. The next step can be continued. Note that the system needs to be turned on before installation.Hyper-V, the opening process is relatively simple, you can refer to other articles.https://segmentfault.com/a/11 …AttentionHyper-VYes andVMwareIs a conflict, the two cannot coexist, can only choose one, if you have to use virtual machines, such asVagrantTools like this can also be run in a virtual machine.Linux systemAnd then according to this article aboutLinux systemThe installation process of is processed and runs in the virtual machine.DockerAs a development environment.
The latest editionDockerThe installation package already containsdocker-compose, there is no need to do extra operations.
After the installation is completed, restart the computer when you see theThe little whaleShowDocker is runningThat is to sayDockerThe launch was successful.


We need to right-clickDocker, clickSign in / Create Docker IDSign in to what we just registeredDocker IDIn order to get the information we can get fromDockerHubGets the permission of the public mirror in the.

Because we are used for development and use, we also need to authorize the permissions of the shared directory, right-clickDockerAnd clickSettings, set the interface to switch toShared Drives, check your project codeDisk drive letter, and click on the lower right cornerApplyThe authorization can be completed.

Swoft development environment

Modify the official defaultdocker-compose.ymlFile

We passed the ordergit clone https://github.com/swoft-cloud/swoftFromGithubonClone SwoftProject, and use the project’s owndocker-compose.ymlFile to implement an environment for development,docker-compose.ymlYesdocker-composeWe will look at the contents of the official default file:

version: '3'
        container_name: swoft
        image: swoft/swoft
            - "80:80"
            - ./:/var/www/swoft
        stdin_open: true
        tty: true
        entrypoint: ["php", "/var/www/swoft/bin/swoft", "start"]

This is a relatively simple layout file, onlyswoftA service is not associated with too much content, aboutdocker-compose.ymlWe don’t give too many explanations on the format of the document, but we can find relevant contents for reading and understanding.
A simple reading of the contents of this document can be understood as usingswoft/swoftThe official image and set the container name asswoftA that binds the inside of the containerEightyPort and hostEightyPorts, settings./The current directory and the/var/www/swoftThe directory is a shared directory, and the interactive terminal with the container is opened and started when arranging files is started.SwoftServices.
We can notice that theentrypointConfiguredphp /var/www/swoft/bin/swoft start, that is to sayStart Swoft serviceBut if onlyCloneProject and executiondocker-compose upTo try to startcontainerIf so, we will get a failed result because it has not been implemented yet.composer installTo loadComposerThe dependence and lack ofvendorFolders andautoloadSuch as related files, resulting in incorrect operationSwoftExample, let’s look at the default layout file settingsstdin_open: trueAndtty: trueTwo parameters, respectivelydockerOn command-iAnd-tTwo parameters, simple understanding is-iOpenInputFunctions,-tOpen a connection container insideInteractive terminal, we can take advantage of these two parameters and arrange theentrypointThe line should readentrypoint: ["sh"]To make the container not start directly after startingSwoftService, but by us manually throughInteractive terminalEnter the container to start. (note that the Swoft official has changed the entry from command to entrypoint, and the corresponding update has been made in this article.)
The following is a modified versiondocker-compose.ymlFile instance:

version: '3'
        container_name: swoft
        image: swoft/swoft
            - "80:80"
            - ./:/var/www/swoft
        stdin_open: true
        tty: true
        entrypoint: ["sh"]

Start the development environment container

At this point we start a in the directory where the files are arranged.Terminal (Shell)And then executedocker-compose up -d,-dThe meaning is toDaemon ModeRunning is convenient for us in the same oneTerminal (Shell)Entering the container, we can see after the command is executed.Starting swoft ... doneThis means that the container was successfully started.
If you get an error when executing the startup command, it indicates that the host’sEightyPort is already occupied, changedocker-compose.ymlWithin the document80:80For other unoccupied ports, note the firstEightyRefers to the port of the host, the secondEightyIt refers to the port in the container, which means we only need to change the first one.

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

Container for entering development environment

Through implementationdocker psThe command can view the container information that was started. The following is sample information:

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

LearnContainer idForf22173763374,Container NameForswoft, we can carry outdocker exec -it f22173763374 bashOrdocker exec -it swoft bashviaInteractive terminalEnter the container.

If an error is reported during executionthe input device is not a TTY. If you are using mintty, try prefixing the command with 'winpty', available atdocker execIncrease before commandwinptyCommand resolution, i.e.winpty docker exec -it swoft bash

Operation, development and debugging

InstallationComposerDependency and GenerationAutoloadFile

viadocker execAfter the command entered the container, we noticed that the contents to the left of the cursor changed toroot@f22173763374:I.e. has entered the container, whereinf22173763374For the correspondingContainer id.
Due toSwoftOfficial mirror imageswoft/swoftThe configured working directory is/var/www/swoft, anddocker-compose.ymlWill againProject current directoryContainers are associated/var/www/swoftDirectory, that is, throughdocker execThe directory entered is already/var/www/swoftDirectory, that is, project directory, so we can directly execute it.composer installCommand to loadComposerThe dependency and generation ofAutoloadDocuments.
Considering the domestic network environment, we are implementingcomposer installThe command can be executed first.composer config -g repo.packagist composer https://packagist.phpcomposer.comCommand configurationComposer China Mirror SourceAccelerating installation speed (since Packagist China mirror source has been unavailable recently, it is recommended to switch to Laravel-China China source, i.e.config -g repo.packagist composer https://packagist.laravel-china.org)。

Start upSwoftService

Installation completedComposerOnce dependent, it can be executedphp bin/swoft startStart the service when you see

root@f22173763374:/var/www/swoft# php bin/swoft start
                         Server Information
* HTTP | host:, port: 80, type: 1, worker: 1, mode: 3
* TCP  | host:, 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.

That means yoursSwoftAnd the launch was successful, we can open the browser to access ithttp:// you see the picture below, you are done!


If the port on which you bind the host is notEighty, you can change to the corresponding;
If what the visit saw wasRedis connection failure host= port=6379This indicates a lack ofRedisService, the simplest and most direct is directly installed in the current containerRedis ServerDirect executionapt install -y redis-server && service redis-server startThe installation and start-up operations can be completed.

Modify the code and make it effective

SwoftwithPHP-FPMThere will be a little difference in the development under the modePHP-FPMUnder the mode of direct change code content, then access to the corresponding code can get the changed content, becausePHP-FPMEach request in mode reloads PHP code, whileSwoftYesPersistent operation, which means that the code does not need to be reloaded after the service is started, and this mode change can makeSwoftOne of the reasons for greatly improving performance is that a large amount of code of can be reused without reloading and re-instantiating.
Such changes will have a certain impact on development, that is to say, inSwoftNext, you need toRestart WorkerOrRestart serviceIn order for the changed code to take effect, but thanks toSwoftTheThermal overloadFunction, can automatically check code changes and automaticallyRestart Worker, we just need to go through the.envFile changesAUTO_RELOADItems aretrueThat is, if there is no one in the root directory of the project.envFiles that can be copied directly.env.exampleThe file is.envAnd make corresponding changes, it is only necessary to pay attention to the changeappThe code in the directory will only beThermal overloadFunction overload, change other code will not be overloaded, this is because different code is in different life cycle, onlyWorkerStartOnly then can the loaded code be reloaded, and we will cover the contents of this part later.Swoft life cycleAt that time, we will give further explanation.