05 Serving Web Files - dchantzis/sfh-docker-in-development-part-1 GitHub Wiki

Source: https://serversforhackers.com/c/div-serving-web-files

Remove the running Container:

docker ps -a
docker stop <CONTAINER_ID> && docker rm <CONTAINER_ID>

We are going to edit the shippingdocker/app image and add some configuration to it. The configuration will be added in the docker/app directory in the default file:

vim docker/app/default

add the following default configuration:

server {
	listen 80 default_server;

	root /var/www/html/public;

	index index.html index.htm index.php;

	server_name _;

	charset utf-8;

	location = /favicon.ico { log_not_found off; access_log off; }
	location = /robots.txt { log_not_found off; access_log off; }

	location / {
		try_files $uri $uri/ /index.php$is_args;$args;
	}

	location ~ \.php$ {
		include snippets/fastcgi-php.conf;
		fastcgi_pass unix:/run/php/php7.2-fpm.sock;
	}

	error_page 404 /index.php;
}

In the Dockerfile we'll write the following to add the file for nginx to use the default configuration:

ADD default /etc/nginx/sites-available/default

To rebuild the image run the following below. This over-writes our current image at tag latest with our changes:

docker build -t shippingdocker/app:latest -f docker/app/Dockerfile docker/app

Add some files in docker/app:

mkdir application
vim application/index.php
vim application/index.html

Contents for application/index.php:

<?php phpinfo();

Contents for application/index.html:

Hello Docker.

Now run Container:

docker run --rm -d -v $(pwd)/application:/var/www/html/public -p 8080:80 shippingdocker/app:latest nginx
  • -p 8080:80 This will forward the port 8080 of my localhost to the port 80 inside of the Container.
  • -v Share a volume. We are sharing the current directory ($(pwd)) and share the application directory inside there (application) to the directory inside the Container (/var/www/html/public) were we set the web-root inside the Container.

Note for the Windows Command Line, you can mount the current directory like so:

-v %cd%/application:/var/www/html/public

For Powershell, use ${PWD}:

-v ${PWD}/application:/var/www/html/public

For Linux, use $(pwd):

-v $(pwd)/application:/var/ww/html/public

With the Container running on port 8080, we can now check the configuration, (or visit localhost:8080 from the browser):

curl localhost:8080

From the browser, running localhost:8080/index.php will result a 502 error. This is because we only told the Container to run nginx If we do docker exec we will execute against an already-running Container (previously done with docker run). We can execute (interactively) bash inside the already-running Container:

docker exec -it <CONTAINER_ID> bash

then to see all the running processes inside the Container:

ps aux

This will show that we are not running php (thus the 502 error above). Php FPM needs to be running to fulfill a php request and we have only specified to run nginx.