Sunday, January 16, 2022

Install swoole on window

 

Not directly, but with Docker and WSL (Windows Subsystem for Linux).

  1. Install Docker (https://www.docker.com/products/docker-desktop)
  2. Setup WSL

Open PowerShell as Administrator and run

Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux

Updating/Install the WSL 2 Linux kernel (https://docs.microsoft.com/en-us/windows/wsl/wsl2-kernel)

  1. Enable "Enable the experimental WSL 2 based engine" in Docker (General)
  2. Build the Docker container

IMPORTANT! Don't use a path with spacebars like:

  • C:\Users\ {FIRSTNAME}[SPACEBAR]{LASTNAME}\Desktop\docker)

Create a folder (D:\docker) and create with an Editor the Dockerfile (D:\docker\Dockerfile)

FROM php:7.4.2-cli

RUN apt-get update && apt-get install vim -y && \
    apt-get install openssl -y && \
    apt-get install libssl-dev -y && \
    apt-get install wget -y && \
    apt-get install git -y && \
    apt-get install procps -y && \
    apt-get install htop -y

RUN cd /tmp && git clone https://github.com/swoole/swoole-src.git && \
    cd swoole-src && \
    git checkout v4.4.15 && \
    phpize  && \
    ./configure  --enable-openssl && \
    make && make install

RUN touch /usr/local/etc/php/conf.d/swoole.ini && \
    echo 'extension=swoole.so' > /usr/local/etc/php/conf.d/swoole.ini

RUN wget -O /usr/local/bin/dumb-init https://github.com/Yelp/dumb-init/releases/download/v1.2.2/dumb-init_1.2.2_amd64
RUN chmod +x /usr/local/bin/dumb-init

RUN apt-get autoremove -y && rm -rf /var/lib/apt/lists/*

ENTRYPOINT ["/usr/local/bin/dumb-init", "--", "php"]

Open PowerShell navigate to your folder (D:\docker) to build the DockerImage

docker build -f ./Dockerfile -t swoole-php .
  1. Add your swoole source code

As an example (D:\docker\server.php)

<?php
$http = new Swoole\HTTP\Server("0.0.0.0", 9501);

$http->on('start', function ($server) {
    echo "Swoole http server is started at http://127.0.0.1:9501\n";
});

$http->on('request', function ($request, $response) {
    $response->header("Content-Type", "text/plain");
    $response->end("Hello World\n");
});

$http->start();
?>
  1. Start your swoole http server with the PowerShell
docker run --rm -p 9501:9501 -v D:/docker/:/app -w /app swoole-php server.php