Install PHP from prebuilt packages on Alpine Linux with Nginx

Install PHP on Alpine Linux

First, let's install PHP. Alpine Linux official repositories contain slightly outdated PHP versions. You can install PHP on Alpine Linux using apk tool:

apk add --no-cache php7

3rd party repository Alpine repository provides the latest PHP versions.

Adding repository to your Alpine:

apk add --no-cache wget ca-certificates \
&& wget -O /etc/apk/keys/ \
&& echo "" >> /etc/apk/repositories PHP packages are prefixed with php7.2, php7.1 and php7.0. Installing latest PHP is as simple as:

apk add --no-cache php7.2

Install nginx

apk add --no-cache nginx


To run PHP via Nginx, you should use the PHP FPM SAPI. To install it, run:

apk add --no-cache php7-fpm

Configure nginx

After successfull installation create a configuration file for your site:

# /etc/nginx/conf.d/default.conf
server {
    root /var/www/app/public;

    location / {
        # try to serve file directly, fallback to index.php
        try_files $uri /index.php$is_args$args;

    location ~ ^/index\.php(/|$) {
        fastcgi_pass unix:/run/php/php-fpm.sock;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;
        # When you are using symlinks to link the document root to the
        # current version of your application, you should pass the real
        # application path instead of the path to the symlink to PHP
        # FPM.
        # Otherwise, PHP's OPcache may not properly detect changes to
        # your PHP files (see
        # for more information).
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $realpath_root;
        # Prevents URIs that include the front controller. This will 404:
        # http://domain.tld/index.php/some-path
        # Remove the internal directive to allow URIs like this

    # return 404 for all other php files not matching the front controller
    # this prevents access to other php files you don't want to be accessible.
    location ~ \.php$ {
        return 404;

Development on localhost using built-in web server

If you're developing PHP applications on your local workstation, PHP also has a useful built-in web server for localhost development. It is not intended to be used for production environments.

Inside your project folder you can run it from the command line using PHP CLI SAPI:

php -S localhost:8000

Visit http://localhost:8000/ in your browser to access it.