Securing a Docker container with HTTP BASIC AUTH

15,638

Solution 1

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".

Solution 2

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).

Share:
15,638
Khozzy
Author by

Khozzy

Updated on June 07, 2022

Comments

  • Khozzy
    Khozzy about 2 years

    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