Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Securing a Docker container with HTTP BASIC AUTH

Consider running a Docker container with a web application exposing a certain port. How to apply the additional security layer before accessing the URL (HTTP BASIC AUTH)?

Docker Engine version >= 1.9.1

like image 203
Khozzy Avatar asked Aug 31 '26 17:08

Khozzy


2 Answers

Typically, you dedicate a container for authentication, with for instance NGiNX.
This is described in "Authenticating proxy with nginx", which not only adds the basic authentication, but also ssl (https)

That web server will then reverse proxy to your container.

You have a more generic solution (based on a reverse-proxy NGiNX) with jwilder/nginx-proxy

nginx-proxy sets up a container running nginx and docker-gen.
docker-gen generates reverse proxy configs for nginx and reloads nginx when containers are started and stopped.

See the use case with "Automated Nginx Reverse Proxy for Docker".

like image 94
VonC Avatar answered Sep 03 '26 15:09

VonC


Here is a config example based on the instructions from jwilder/nginx-proxy Basic Auth support:

The docker-compose.yml file (to be used by running docker-compose up -d):

version: '2.1'

services:
  nginx-proxy:
    container_name: nginx-proxy
    restart: always
    image: jwilder/nginx-proxy
    networks: 
      - proxynet
    ports:
      - "80:80"
    volumes:
      - /srv/docker/nginx/htpasswd:/etc/nginx/htpasswd
      - /etc/nginx/vhost.d
      - /usr/share/nginx/html
      - /var/run/docker.sock:/tmp/docker.sock:ro

networks:
  proxynet:
    external: true

And here is a simple container that uses that proxy for the domain name www.example.com:

version: '3.3'

services:
   example:
     container_name: www.example.com
     image: php:7.2-apache
     restart: always
     networks:
       - proxynet
     expose:
       - "80"
     environment:
       - VIRTUAL_HOST=www.example.com
       - VIRTUAL_PORT=80

networks:
  proxynet:
    external: true

Under /srv/docker/nginx/htpasswd/, place a www.example.com file, containing:

test:wTVo4pnGgDWBo

Accessing http://www.example.com (to be replaced with your actual domain name), you'll then be prompted for a username and a password (test:test in this case).

like image 39
Cédric Françoys Avatar answered Sep 03 '26 15:09

Cédric Françoys



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!