Protect your web server with HTTP authentication
Note
Clone the git repository if you haven’t done it yet.
Go to Project 7 from the git repository root:
cd projects/p07
Project structure:
.
├── nginxproxy
│ └── docker-compose.yml
└── web
├── .env
├── docker-compose.yml
└── www
└── index.html
The first step is the same as it was in Run multiple Docker Compose projects on the same port using nginx-proxy. Let’s go to nginxproxy
cd nginxproxy
The compose file is:
name: p07proxy
networks:
default:
external: true
name: public_proxy
services:
nginx-proxy:
image: nginxproxy/nginx-proxy:1.2.0
ports:
- "80:80"
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
Start the proxy server:
docker compose up -d
Go to the web folder:
cd ../web
The compose file is
name: p07web
volumes:
apache2:
networks:
proxy:
external: true
name: public_proxy
services:
htpasswd:
image: rimelek/httpd24:2.0
volumes:
- apache2:/usr/local/apache2
command:
- "/bin/bash"
- "-c"
- "htpasswd -nb $HTTPD_USER $HTTPD_PASS >> /usr/local/apache2/.htpasswd"
network_mode: none
httpd:
depends_on:
- htpasswd
image: rimelek/httpd24:2.0
volumes:
- apache2:/usr/local/apache2
- ./www:/usr/local/apache2/htdocs
networks:
- proxy
environment:
SRV_AUTH: "true"
VIRTUAL_HOST: p07.$NIP
fixperm:
depends_on:
- httpd
image: bash
volumes:
- ./www:/htdocs
network_mode: none
command:
- "bash"
- "-c"
- "find htdocs/ -type f -exec chmod -R 0655 {} \\; && chmod 0775 /htdocs && chown -R 33:33 /htdocs"
In this case we have a simple html file
<p style="text-align: center; font-size: 20pt">Hello Docker User!</p>
You can simply start a web server protected by HTTP authentication. The name and the password will come from environment variables. I recommend you to use a more secure way in production. Create the .htpasswd file manually and mount it inside the container.
The htpasswd container will create .htpasswd automatically and exit.
In the “.env” file you can find two variables.
HTTPD_USER=user
HTTPD_PASS=secretpass
The variables will be used in “docker-compose.yml” by the “htpasswd” service to generate the password file and then the “httpd” service will read it from the common volume.
The “fixperm” service runs and exits similarly to “htpasswd”. It sets the permission of the files after the web server starts.
Use the “depends_on” option to control which service starts first.
At this point you need to have the NIP variable set as the Welcome to Learn Docker’s documentation! refers to it.
Alternative option: set the NIP variable in the “.env” file.
Start the web server
docker compose up -d
In case are working the in cloned repository of this tutorial, you can also run the below command to set the variable
NIP=$(../../../system/usr/local/bin/nip.sh) docker compose up -d
Open the web page in your browser (Ex.: p07.192.168.1.6.nip.io). You will get a password prompt.
Clean the project:
docker compose down --volumes
cd ../nginxproxy
docker compose down --volumes