Posted on: April 05, 2023 06:37 PM
Posted by: Renato
Categories: Laravel phpswoole laraveloctane Swoole Swoole PHP Swoole octane Docker sail
Views: 1695
Laravel Octane Swoole em ambiente Laravel Sail - Tutorial Passo a Passo para Configuração
#laravel #phpswoole #laraveloctane
Laravel Sail with HTTPS Swoole
MA maioria dos aplicativos PHP são hospedados na pilha LAMP ou LEMP , a combinação Nginx+PHP-FPM é rápida, fácil de configurar e popular hoje em dia. No entanto, surgiu o divisor de águas para o PHP — Swoole . Ele nos traz capacidade assíncrona, multithreading real e excelente desempenho de simultaneidade para PHP!
Victor Gazotti & Eldad A. Fux testaram com 80% ~ 91% de ganho de performance ! Parece PHP com esteróides!
📝 Se você é um novato, sinta-se à vontade para ler o Kickstart your Laravel Web App using Laravel Sail .
A documentação oficial do Laravel não fornece o método ( atualmente ainda não suportado ) para configurar o Swoole no modo HTTPS .
0. Crie seu projeto Laravel
Apenas uma nota rápida para criar um projeto em branco
cd ~/codecurl -s https://laravel.build/test-project | bashcd test-projectsail up -d
1. Install Laravel Octane
Install the Laravel Octane with
sail composer require laravel/octane
and then
sail artisan octane:install
Use code . command open the VS Code.
1.1 Octane Config File
✏️ Append/Edit in config/octane.php file
| /* | |
| |-------------------------------------------------------------------------- | |
| | Octane Swoole Configuration Options | |
| |-------------------------------------------------------------------------- | |
| | | |
| | While using Swoole, you may define additional configuration options as | |
| | required by the application. You maycheck which options you need from: | |
| | https://www.swoole.co.uk/docs/modules/swoole-server/configuration | |
| | | |
| */ | |
| 'swoole' => [ | |
| 'ssl' => true, | |
| 'options' => [ | |
| 'ssl_cert_file' => '/etc/swoole/ssl/certs/sail-selfsigned.crt', | |
| 'ssl_key_file' => '/etc/swoole/ssl/private/sail-selfsigned.key', | |
| ] | |
| ], |
Configurando as opções necessárias para protocolos HTTPS, o certificado e a chave SSL serão gerados pelos comandos no arquivo Dockerfile. Você pode ativar/desativar a funcionalidade HTTPS SSL alterando o valor e enable-opensslreiniciando os contêineres.
2. Configuração do arquivo ENV
✏️ Anexar no .envarquivo
Use Swoole como o servidor Octane. O sinalizador OCTANE_HTTPSnão está ativando a funcionalidade SSL, é apenas sobre o prefixo da URL, você pode ler isto .
| OCTANE_SERVER=swoole | |
| OCTANE_HTTPS=true |
3. Mantenha o Swoole funcionando
Vou usar o Laravel Octane para substituir o servidor HTTP interno do PHP, precisamos sempre manter o Octane funcionando.
Preciso personalizar nosso Sail publicando os arquivos de configuração:
sail artisan sail:publish
So, ✏️update docker/8.0/supervisord.conf (Line 8) as stated in official documentation.
| command=/usr/bin/php -d variables_order=EGPCS /var/www/html/artisan octane:start --server=swoole --host=0.0.0.0 --port=8000 --watch |
O Octane precisa reiniciar para aplicar as alterações no arquivo, então também ativei o --watchsinalizador no comando acima. No entanto, certifique-se de instalar a biblioteca de monitoramento de arquivos Chokidar também, você pode ler mais em documentos oficiais .
sail npm install --save-dev chokidar
4. Configuração do Docker
A. ✏️ Anexar no docker-compose.ymlarquivo, portsseção (~ Linha 13)
Eu preciso mapear a porta 8000para público
| ports: | |
| - '${APP_PORT:-80}:80' | |
| - 8000:8000 |
Para fazer com que todas as configurações acima funcionem corretamente, preciso modificar o arquivo docker/8.0/Dockerfile.
B. ✏️ Anexar linhas para certificado autoassinado SSL com permissão de pasta apropriada
Você tem que atualizar a versão mais recente do Sail (> v1.8.4) que inclui o pacote
php8.0-swoolesemaptpecl
Após a criação do usuário sail (~Linha 47) —
RUN useradd -ms /bin/bash — no-user-group -g $WWWGROUP -u 1337 sail
adicione essas linhas...
RUN mkdir -p /etc/swoole/ssl/certs/ /etc/swoole/ssl/private/
RUN openssl req -x509 -nodes -days 365 -subj "/C=CA/ST=QC/O=Artisan, Inc./CN=localhost" \
-addext "subjectAltName=DNS:localhost" -newkey rsa:2048 \
-keyout /etc/swoole/ssl/private/sail-selfsigned.key \
-out /etc/swoole/ssl/certs/sail-selfsigned.crt;
RUN chmod 644 /etc/swoole/ssl/certs/*.crt
RUN chown -R root:sail /etc/swoole/ssl/private/
RUN chmod 640 /etc/swoole/ssl/private/*.key
O resultante Dockerfile:
| FROM ubuntu:21.04 | |
| LABEL maintainer="Taylor Otwell" | |
| ARG WWWGROUP | |
| WORKDIR /var/www/html | |
| ENV DEBIAN_FRONTEND noninteractive | |
| ENV TZ=UTC | |
| RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone | |
| RUN apt-get update \ | |
| && apt-get install -y gnupg gosu curl ca-certificates zip unzip git supervisor sqlite3 libcap2-bin libpng-dev python2 \ | |
| && mkdir -p ~/.gnupg \ | |
| && chmod 600 ~/.gnupg \ | |
| && echo "disable-ipv6" >> ~/.gnupg/dirmngr.conf \ | |
| && apt-key adv --homedir ~/.gnupg --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys E5267A6C \ | |
| && apt-key adv --homedir ~/.gnupg --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys C300EE8C \ | |
| && echo "deb http://ppa.launchpad.net/ondrej/php/ubuntu hirsute main" > /etc/apt/sources.list.d/ppa_ondrej_php.list \ | |
| && apt-get update \ | |
| && apt-get install -y php8.0-cli php8.0-dev \ | |
| php8.0-pgsql php8.0-sqlite3 php8.0-gd \ | |
| php8.0-curl php8.0-memcached \ | |
| php8.0-imap php8.0-mysql php8.0-mbstring \ | |
| php8.0-xml php8.0-zip php8.0-bcmath php8.0-soap \ | |
| php8.0-intl php8.0-readline php8.0-pcov \ | |
| php8.0-msgpack php8.0-igbinary php8.0-ldap \ | |
| php8.0-redis php8.0-swoole \ | |
| && php -r "readfile('http://getcomposer.org/installer');" | php -- --install-dir=/usr/bin/ --filename=composer \ | |
| && curl -sL https://deb.nodesource.com/setup_16.x | bash - \ | |
| && apt-get install -y nodejs \ | |
| && curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - \ | |
| && echo "deb https://dl.yarnpkg.com/debian/ stable main" > /etc/apt/sources.list.d/yarn.list \ | |
| && apt-get update \ | |
| && apt-get install -y yarn \ | |
| && apt-get install -y mysql-client \ | |
| && apt-get install -y postgresql-client \ | |
| && apt-get -y autoremove \ | |
| && apt-get clean \ | |
| && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* | |
| RUN setcap "cap_net_bind_service=+ep" /usr/bin/php8.0 | |
| RUN groupadd --force -g $WWWGROUP sail | |
| RUN useradd -ms /bin/bash --no-user-group -g $WWWGROUP -u 1337 sail | |
| RUN mkdir -p /etc/swoole/ssl/certs/ /etc/swoole/ssl/private/ | |
| RUN openssl req -x509 -nodes -days 365 -subj "/C=CA/ST=QC/O=Artisan, Inc./CN=localhost" \ | |
| -addext "subjectAltName=DNS:localhost" -newkey rsa:2048 \ | |
| -keyout /etc/swoole/ssl/private/sail-selfsigned.key \ | |
| -out /etc/swoole/ssl/certs/sail-selfsigned.crt; | |
| RUN chmod 644 /etc/swoole/ssl/certs/*.crt | |
| RUN chown -R root:sail /etc/swoole/ssl/private/ | |
| RUN chmod 640 /etc/swoole/ssl/private/*.key | |
| COPY start-container /usr/local/bin/start-container | |
| COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf | |
| COPY php.ini /etc/php/8.0/cli/conf.d/99-sail.ini | |
| RUN chmod +x /usr/local/bin/start-container | |
| EXPOSE 8000 | |
| ENTRYPOINT ["start-container"] |
5. Recrie o contêiner
Encerre seu contêiner com, sail downem seguida, reconstrua com
sail build --no-cache
6. Teste
Seu Swoole deve estar funcionando, você pode verificar com
sail artisan octane:status
e também abrir o navegador e entrar https://localhost:8000, deve abrir a página de boas-vindas de Laravel com HTTPS.
Também faço o teste usando ab, para saber quanto ganho de desempenho.
ab -n 10000 -c 512 -H "Accept-Encoding: gzip, deflate" https://localhost:8000/
Result:
Server Software: swoole-http-server
Server Hostname: localhost
Server Port: 8000
SSL/TLS Protocol: TLSv1.2,ECDHE-RSA-AES256-GCM-SHA384,2048,256
Server Temp Key: X25519 253 bits
TLS Server Name: localhostDocument Path: /
Document Length: 17503 bytesConcurrency Level: 512
Time taken for tests: 97.184 seconds
Complete requests: 10000
Failed requests: 0
Total transferred: 185930000 bytes
HTML transferred: 175030000 bytes
Requests per second: 102.90 [#/sec] (mean)
Time per request: 4975.846 [ms] (mean)
Time per request: 9.718 [ms] (mean, across all concurrent requests)
Transfer rate: 1868.33 [Kbytes/sec] receivedConnection Times (ms)
min mean[+/-sd] median max
Connect: 2 30 96.9 3 633
Processing: 56 4794 2417.4 4598 19666
Waiting: 17 4791 2418.0 4586 19665
Total: 60 4824 2403.2 4613 19668Percentage of the requests served within a certain time (ms)
50% 4613
66% 5592
75% 6085
80% 6398
90% 7509
95% 8599
98% 10384
99% 12929
100% 19668 (longest request)
As the baseline: the default PHP built-in server
ab -n 10000 -c 512 -H "Accept-Encoding: gzip, deflate" http://localhost/
Result:
Server Software:
Server Hostname: localhost
Server Port: 80Document Path: /
Document Length: 17490 bytesConcurrency Level: 512
Time taken for tests: 198.809 seconds
Complete requests: 10000
Failed requests: 0
Total transferred: 186310000 bytes
HTML transferred: 174900000 bytes
Requests per second: 50.30 [#/sec] (mean)
Time per request: 10179.014 [ms] (mean)
Time per request: 19.881 [ms] (mean, across all concurrent requests)
Transfer rate: 915.17 [Kbytes/sec] receivedConnection Times (ms)
min mean[+/-sd] median max
Connect: 0 0 1.4 0 9
Processing: 26 9913 1863.2 10041 13891
Waiting: 15 9912 1863.2 10041 13890
Total: 28 9913 1862.1 10041 13891Percentage of the requests served within a certain time (ms)
50% 10041
66% 10549
75% 11006
80% 11085
90% 11833
95% 12221
98% 12640
99% 13391
100% 13891 (longest request)
Conclude the results

.Pode ver que o pedido por segundo é melhorado mais de 100% 🤩! O tempo total é levado e o tempo/pedido é também reduzido para metade! Este Swoole está apenas a tomar as configurações padrão, pode afiná-lo com base nos seus requisitos para alcançar um resultado mais desejável!
Fonte:
- https://blog.devgenius.io/laravel-sail-with-https-swoole-ddab7f5303ec
Donate to Site
Renato
Developer
-
Renato Lucena - há 3 anos
=> https://gist.github.com/lucenarenato/95ee3b6b8c16907dd6ee5a415475eb55