Merge remote-tracking branch 'upstream/main' into merge_upstream

This commit is contained in:
Robin Windey 2022-02-20 12:17:29 +01:00
commit 28c4a0d80a
No known key found for this signature in database
GPG key ID: 35D381829B5DF829
94 changed files with 1626 additions and 711 deletions

View file

@ -1,14 +1,35 @@
# !!!PLEASE READ!!!
# ⚠️ PLEASE READ ⚠️
## Questions
## Questions or Features
If you have a question, DO NOT SUBMIT a new issue. Please ask the question on the Q&A Group: https://groups.google.com/forum/#!forum/nginx-proxy
If you have a question or want to request a feature, please **DO NOT SUBMIT** a new issue.
## Bugs or Features
Instead please use the relevant Discussions section's category:
- 🙏 [Ask a question](https://github.com/nginx-proxy/nginx-proxy/discussions/categories/q-a)
- 💡 [Request a feature](https://github.com/nginx-proxy/nginx-proxy/discussions/categories/ideas)
If you are logging a bug or feature request, please search the current open issues to see if there is already a bug or feature opened.
## Bugs
For bugs, the easier you make it to reproduce the issue you see, the easier and faster it can get fixed. If you can provide a script or docker-compose file that reproduces the problems, that is very helpful.
If you are logging a bug, please search the current open issues first to see if there is already a bug opened.
For bugs, the easier you make it to reproduce the issue you see and the more initial information you provide, the easier and faster the bug can be identified and can get fixed.
Please at least provide:
- the exact nginx-proxy version you're using (if using `latest` please make sure it is up to date and provide the version number printed at container startup).
- complete configuration (compose file, command line, etc) of both your nginx-proxy container(s) and proxied containers. You should redact sensitive info if needed but please provide **full** configurations.
- generated nginx configuration obtained with `docker exec nameofyournginxproxycontainer nginx -T`
If you can provide a script or docker-compose file that reproduces the problems, that is very helpful.
## General advice about `latest`
Do not use the `latest` tag for production setups.
`latest` is nothing more than a convenient default used by Docker if no specific tag is provided, there isn't any strict convention on what goes into this tag over different projects, and it does not carry any promise of stability.
Using `latest` will most certainly put you at risk of experiencing uncontrolled updates to non backward compatible versions (or versions with breaking changes) and makes it harder for maintainers to track which exact version of the container you are experiencing an issue with.
This recommendation stands for pretty much every Docker image in existence, not just nginx-proxy's ones.
Thanks,
Jason
Nicolas

View file

@ -7,5 +7,13 @@ updates:
schedule:
interval: "daily"
labels:
- "area/chore"
- "area/dockerfile"
- "type/build"
- "scope/dockerfile"
# Maintain Python dependencies (test suite)
- package-ecosystem: "pip"
directory: "/test/requirements"
schedule:
interval: "daily"
labels:
- "type/ci"

View file

@ -2,9 +2,11 @@ name: DockerHub
on:
workflow_dispatch:
schedule:
- cron: '0 0 * * 1'
push:
branches:
- master
- main
tags:
- '*.*.*'
paths-ignore:
@ -18,7 +20,7 @@ on:
- '*.md'
jobs:
multiarch-build:
multiarch-build-debian:
runs-on: ubuntu-latest
steps:
@ -27,9 +29,12 @@ jobs:
with:
fetch-depth: 0
- name: Retrieve version
run: echo "GIT_DESCRIBE=$(git describe --tags)" >> $GITHUB_ENV
- name: Get Docker tags for Debian based image
id: docker_meta_debian
uses: crazy-max/ghaction-docker-meta@v2
uses: docker/metadata-action@v3
with:
images: |
nginxproxy/nginx-proxy
@ -38,19 +43,9 @@ jobs:
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=raw,value=latest,enable=${{ endsWith(github.ref, github.event.repository.default_branch) }}
- name: Get Docker tags for Alpine based image
id: docker_meta_alpine
uses: crazy-max/ghaction-docker-meta@v2
with:
images: |
nginxproxy/nginx-proxy
jwilder/nginx-proxy
tags: |
type=semver,suffix=-alpine,pattern={{version}}
type=semver,suffix=-alpine,pattern={{major}}.{{minor}}
type=raw,value=alpine,enable=${{ endsWith(github.ref, github.event.repository.default_branch) }}
flavor: latest=false
labels: |
org.opencontainers.image.authors=Nicolas Duchon <nicolas.duchon@gmail.com> (@buchdag), Jason Wilder
org.opencontainers.image.version=${{ env.GIT_DESCRIBE }}
- name: Set up QEMU
uses: docker/setup-qemu-action@v1
@ -68,23 +63,68 @@ jobs:
id: docker_build_debian
uses: docker/build-push-action@v2
with:
context: .
file: Dockerfile
build-args: NGINX_PROXY_VERSION=${{ env.GIT_DESCRIBE }}
platforms: linux/amd64,linux/arm64,linux/arm/v7
push: true
tags: ${{ steps.docker_meta_debian.outputs.tags }}
labels: ${{ steps.docker_meta_debian.outputs.labels }}
- name: Images digests
run: echo ${{ steps.docker_build_debian.outputs.digest }}
multiarch-build-alpine:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Retrieve version
run: echo "GIT_DESCRIBE=$(git describe --tags)" >> $GITHUB_ENV
- name: Get Docker tags for Alpine based image
id: docker_meta_alpine
uses: docker/metadata-action@v3
with:
images: |
nginxproxy/nginx-proxy
jwilder/nginx-proxy
tags: |
type=semver,suffix=-alpine,pattern={{version}}
type=semver,suffix=-alpine,pattern={{major}}.{{minor}}
type=raw,value=alpine,enable=${{ endsWith(github.ref, github.event.repository.default_branch) }}
labels: |
org.opencontainers.image.authors=Nicolas Duchon <nicolas.duchon@gmail.com> (@buchdag), Jason Wilder
org.opencontainers.image.version=${{ env.GIT_DESCRIBE }}
flavor: latest=false
- name: Set up QEMU
uses: docker/setup-qemu-action@v1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
- name: Login to DockerHub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and push the Alpine based image
id: docker_build_alpine
uses: docker/build-push-action@v2
with:
context: .
file: Dockerfile.alpine
build-args: NGINX_PROXY_VERSION=${{ env.GIT_DESCRIBE }}
platforms: linux/amd64,linux/arm64,linux/arm/v7
push: true
tags: ${{ steps.docker_meta_alpine.outputs.tags }}
labels: ${{ steps.docker_meta_alpine.outputs.labels }}
- name: Images digests
run: |
echo ${{ steps.docker_build_debian.outputs.digest }}
echo ${{ steps.docker_build_alpine.outputs.digest }}
run: echo ${{ steps.docker_build_alpine.outputs.digest }}

View file

@ -1,22 +0,0 @@
dist: trusty
sudo: required
env:
matrix:
- TEST_TARGET: test-debian
- TEST_TARGET: test-alpine
before_install:
- sudo apt-get -y remove docker docker-engine docker-ce
- sudo rm /etc/apt/sources.list.d/docker.list
- curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
- sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
- sudo apt-get update
- sudo apt-get -y install docker-ce
- docker version
- docker info
# prepare docker test requirements
- make update-dependencies
script:
- make $TEST_TARGET

View file

@ -1,79 +1,74 @@
# setup build arguments for version of dependencies to use
ARG DOCKER_GEN_VERSION=0.7.4
ARG FOREGO_VERSION=0.16.1
ARG DOCKER_GEN_VERSION=0.7.7
ARG FOREGO_VERSION=v0.17.0
# Use a specific version of golang to build both binaries
FROM golang:1.15.10 as gobuilder
FROM golang:1.16.7 as gobuilder
# Build docker-gen from scratch
FROM gobuilder as dockergen
# Download the sources for the given version
ARG DOCKER_GEN_VERSION
ADD https://github.com/jwilder/docker-gen/archive/${DOCKER_GEN_VERSION}.tar.gz sources.tar.gz
# Move the sources into the right directory
RUN tar -xzf sources.tar.gz && \
mkdir -p /go/src/github.com/jwilder/ && \
mv docker-gen-* /go/src/github.com/jwilder/docker-gen
# Install the dependencies and make the docker-gen executable
WORKDIR /go/src/github.com/jwilder/docker-gen
RUN go get -v ./... && \
CGO_ENABLED=0 GOOS=linux go build -ldflags "-X main.buildVersion=${DOCKER_GEN_VERSION}" ./cmd/docker-gen
RUN git clone https://github.com/nginx-proxy/docker-gen \
&& cd /go/docker-gen \
&& git -c advice.detachedHead=false checkout $DOCKER_GEN_VERSION \
&& go mod download \
&& CGO_ENABLED=0 GOOS=linux go build -ldflags "-X main.buildVersion=${DOCKER_GEN_VERSION}" ./cmd/docker-gen \
&& go clean -cache \
&& mv docker-gen /usr/local/bin/ \
&& cd - \
&& rm -rf /go/docker-gen
# Build forego from scratch
# Because this relies on golang workspaces, we need to use go < 1.8.
FROM gobuilder as forego
# Download the sources for the given version
ARG FOREGO_VERSION
ADD https://github.com/jwilder/forego/archive/v${FOREGO_VERSION}.tar.gz sources.tar.gz
# Move the sources into the right directory
RUN tar -xzf sources.tar.gz && \
mkdir -p /go/src/github.com/ddollar/ && \
mv forego-* /go/src/github.com/ddollar/forego
# Install the dependencies and make the forego executable
WORKDIR /go/src/github.com/ddollar/forego/
RUN go get -v ./... && \
CGO_ENABLED=0 GOOS=linux go build -o forego .
RUN git clone https://github.com/nginx-proxy/forego/ \
&& cd /go/forego \
&& git -c advice.detachedHead=false checkout $FOREGO_VERSION \
&& go mod download \
&& CGO_ENABLED=0 GOOS=linux go build -o forego . \
&& go clean -cache \
&& mv forego /usr/local/bin/ \
&& cd - \
&& rm -rf /go/forego
# Build the final image
FROM nginx:1.19.3
LABEL maintainer="Jason Wilder mail@jasonwilder.com"
FROM nginx:1.21.6
ARG NGINX_PROXY_VERSION
# Add DOCKER_GEN_VERSION environment variable
# Because some external projects rely on it
ARG DOCKER_GEN_VERSION
ENV NGINX_PROXY_VERSION=${NGINX_PROXY_VERSION} \
DOCKER_GEN_VERSION=${DOCKER_GEN_VERSION} \
DOCKER_HOST=unix:///tmp/docker.sock
# Install wget and install/updates certificates
RUN apt-get update \
&& apt-get install -y -q --no-install-recommends \
ca-certificates \
wget \
&& apt-get clean \
&& rm -r /var/lib/apt/lists/*
&& apt-get install -y -q --no-install-recommends \
ca-certificates \
wget \
&& apt-get clean \
&& rm -r /var/lib/apt/lists/*
# Configure Nginx and apply fix for very long server names
RUN echo "daemon off;" >> /etc/nginx/nginx.conf \
&& sed -i 's/worker_processes 1/worker_processes auto/' /etc/nginx/nginx.conf
&& sed -i 's/worker_processes 1/worker_processes auto/' /etc/nginx/nginx.conf \
&& sed -i 's/worker_connections 1024/worker_connections 10240/' /etc/nginx/nginx.conf \
&& mkdir -p '/etc/nginx/dhparam'
# Install Forego + docker-gen
COPY --from=forego /go/src/github.com/ddollar/forego/forego /usr/local/bin/forego
COPY --from=dockergen /go/src/github.com/jwilder/docker-gen/docker-gen /usr/local/bin/docker-gen
# Add DOCKER_GEN_VERSION environment variable
# Because some external projects rely on it
ARG DOCKER_GEN_VERSION
ENV DOCKER_GEN_VERSION=${DOCKER_GEN_VERSION}
COPY --from=forego /usr/local/bin/forego /usr/local/bin/forego
COPY --from=dockergen /usr/local/bin/docker-gen /usr/local/bin/docker-gen
COPY network_internal.conf /etc/nginx/
COPY . /app/
WORKDIR /app/
ENV DOCKER_HOST unix:///tmp/docker.sock
VOLUME ["/etc/nginx/certs", "/etc/nginx/dhparam"]
ENTRYPOINT ["/app/docker-entrypoint.sh"]
CMD ["forego", "start", "-r"]

View file

@ -1,77 +1,71 @@
# setup build arguments for version of dependencies to use
ARG DOCKER_GEN_VERSION=0.7.4
ARG FOREGO_VERSION=0.16.1
ARG DOCKER_GEN_VERSION=0.7.7
ARG FOREGO_VERSION=v0.17.0
# Use a specific version of golang to build both binaries
FROM golang:1.15.10-alpine as gobuilder
RUN apk add --no-cache git
FROM golang:1.16.7-alpine as gobuilder
RUN apk add --no-cache git musl-dev
# Build docker-gen from scratch
FROM gobuilder as dockergen
# Download the sources for the given version
ARG DOCKER_GEN_VERSION
ADD https://github.com/jwilder/docker-gen/archive/${DOCKER_GEN_VERSION}.tar.gz sources.tar.gz
# Move the sources into the right directory
RUN tar -xzf sources.tar.gz && \
mkdir -p /go/src/github.com/jwilder/ && \
mv docker-gen-* /go/src/github.com/jwilder/docker-gen
# Install the dependencies and make the docker-gen executable
WORKDIR /go/src/github.com/jwilder/docker-gen
RUN go get -v ./... && \
CGO_ENABLED=0 GOOS=linux go build -ldflags "-X main.buildVersion=${DOCKER_GEN_VERSION}" ./cmd/docker-gen
RUN git clone https://github.com/nginx-proxy/docker-gen \
&& cd /go/docker-gen \
&& git -c advice.detachedHead=false checkout $DOCKER_GEN_VERSION \
&& go mod download \
&& CGO_ENABLED=0 go build -ldflags "-X main.buildVersion=${DOCKER_GEN_VERSION}" ./cmd/docker-gen \
&& go clean -cache \
&& mv docker-gen /usr/local/bin/ \
&& cd - \
&& rm -rf /go/docker-gen
# Build forego from scratch
# Because this relies on golang workspaces, we need to use go < 1.8.
FROM gobuilder as forego
# Download the sources for the given version
ARG FOREGO_VERSION
ADD https://github.com/jwilder/forego/archive/v${FOREGO_VERSION}.tar.gz sources.tar.gz
# Move the sources into the right directory
RUN tar -xzf sources.tar.gz && \
mkdir -p /go/src/github.com/ddollar/ && \
mv forego-* /go/src/github.com/ddollar/forego
# Install the dependencies and make the forego executable
WORKDIR /go/src/github.com/ddollar/forego/
RUN go get -v ./... && \
CGO_ENABLED=0 GOOS=linux go build -o forego .
RUN git clone https://github.com/nginx-proxy/forego/ \
&& cd /go/forego \
&& git -c advice.detachedHead=false checkout $FOREGO_VERSION \
&& go mod download \
&& CGO_ENABLED=0 go build -o forego . \
&& go clean -cache \
&& mv forego /usr/local/bin/ \
&& cd - \
&& rm -rf /go/forego
# Build the final image
FROM nginx:1.19.3-alpine
LABEL maintainer="Jason Wilder mail@jasonwilder.com"
# Install wget and install/updates certificates
RUN apk add --no-cache --virtual .run-deps \
ca-certificates bash wget openssl \
&& update-ca-certificates
# Configure Nginx and apply fix for very long server names
RUN echo "daemon off;" >> /etc/nginx/nginx.conf \
&& sed -i 's/worker_processes 1/worker_processes auto/' /etc/nginx/nginx.conf
# Install Forego + docker-gen
COPY --from=forego /go/src/github.com/ddollar/forego/forego /usr/local/bin/forego
COPY --from=dockergen /go/src/github.com/jwilder/docker-gen/docker-gen /usr/local/bin/docker-gen
FROM nginx:1.21.6-alpine
ARG NGINX_PROXY_VERSION
# Add DOCKER_GEN_VERSION environment variable
# Because some external projects rely on it
ARG DOCKER_GEN_VERSION
ENV DOCKER_GEN_VERSION=${DOCKER_GEN_VERSION}
ENV NGINX_PROXY_VERSION=${NGINX_PROXY_VERSION} \
DOCKER_GEN_VERSION=${DOCKER_GEN_VERSION} \
DOCKER_HOST=unix:///tmp/docker.sock
# Install wget and install/updates certificates
RUN apk add --no-cache --virtual .run-deps \
ca-certificates bash wget openssl \
&& update-ca-certificates
# Configure Nginx and apply fix for very long server names
RUN echo "daemon off;" >> /etc/nginx/nginx.conf \
&& sed -i 's/worker_processes 1/worker_processes auto/' /etc/nginx/nginx.conf \
&& sed -i 's/worker_connections 1024/worker_connections 10240/' /etc/nginx/nginx.conf \
&& mkdir -p '/etc/nginx/dhparam'
# Install Forego + docker-gen
COPY --from=forego /usr/local/bin/forego /usr/local/bin/forego
COPY --from=dockergen /usr/local/bin/docker-gen /usr/local/bin/docker-gen
COPY network_internal.conf /etc/nginx/
COPY . /app/
WORKDIR /app/
ENV DOCKER_HOST unix:///tmp/docker.sock
VOLUME ["/etc/nginx/certs", "/etc/nginx/dhparam"]
ENTRYPOINT ["/app/docker-entrypoint.sh"]
CMD ["forego", "start", "-r"]

View file

@ -1,6 +1,7 @@
The MIT License (MIT)
Copyright (c) 2014 Jason Wilder
Copyright (c) 2014-2020 Jason Wilder
Copyright (c) 2021-2022 Nicolas Duchon
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View file

@ -2,15 +2,19 @@
.PHONY : test-debian test-alpine test
update-dependencies:
test/requirements/build.sh
build-webserver:
docker build -t web test/requirements/web
test-debian: update-dependencies
docker build -t nginxproxy/nginx-proxy:test .
build-nginx-proxy-test-debian:
docker build --build-arg NGINX_PROXY_VERSION="test" -t nginxproxy/nginx-proxy:test .
build-nginx-proxy-test-alpine:
docker build --build-arg NGINX_PROXY_VERSION="test" -f Dockerfile.alpine -t nginxproxy/nginx-proxy:test .
test-debian: build-webserver build-nginx-proxy-test-debian
test/pytest.sh
test-alpine: update-dependencies
docker build -f Dockerfile.alpine -t nginxproxy/nginx-proxy:test .
test-alpine: build-webserver build-nginx-proxy-test-alpine
test/pytest.sh
test: test-debian test-alpine

349
README.md
View file

@ -6,27 +6,35 @@ To push a new version to docker hub just create a new tag like `v1.0.1`. Github
it to the docker hub automatically. See `.github/workflows/docker_push.yml` for details.
# Original Readme
![latest 0.8.0](https://img.shields.io/badge/latest-0.8.0-green.svg?style=flat)
![nginx 1.19.3](https://img.shields.io/badge/nginx-1.19.3-brightgreen.svg) ![License MIT](https://img.shields.io/badge/license-MIT-blue.svg) [![Build Status](https://travis-ci.org/jwilder/nginx-proxy.svg?branch=master)](https://travis-ci.org/jwilder/nginx-proxy) [![](https://img.shields.io/docker/stars/jwilder/nginx-proxy.svg)](https://hub.docker.com/r/nginxproxy/nginx-proxy 'DockerHub') [![](https://img.shields.io/docker/pulls/jwilder/nginx-proxy.svg)](https://hub.docker.com/r/nginxproxy/nginx-proxy 'DockerHub')
![nginx 1.21.5](https://img.shields.io/badge/nginx-1.21.5-brightgreen.svg)
[![Docker Image Size](https://img.shields.io/docker/image-size/nginxproxy/nginx-proxy?sort=semver)](https://hub.docker.com/r/nginxproxy/nginx-proxy "Click to view the image on Docker Hub")
[![Docker stars](https://img.shields.io/docker/stars/nginxproxy/nginx-proxy.svg)](https://hub.docker.com/r/nginxproxy/nginx-proxy 'DockerHub')
[![Docker pulls](https://img.shields.io/docker/pulls/nginxproxy/nginx-proxy.svg)](https://hub.docker.com/r/nginxproxy/nginx-proxy 'DockerHub')
nginx-proxy sets up a container running nginx and [docker-gen][1]. docker-gen generates reverse proxy configs for nginx and reloads nginx when containers are started and stopped.
nginx-proxy sets up a container running nginx and [docker-gen](https://github.com/nginx-proxy/docker-gen). docker-gen generates reverse proxy configs for nginx and reloads nginx when containers are started and stopped.
See [Automated Nginx Reverse Proxy for Docker][2] for why you might want to use this.
See [Automated Nginx Reverse Proxy for Docker](http://jasonwilder.com/blog/2014/03/25/automated-nginx-reverse-proxy-for-docker/) for why you might want to use this.
### Usage
To run it:
$ docker run -d -p 80:80 -v /var/run/docker.sock:/tmp/docker.sock:ro nginxproxy/nginx-proxy
```console
docker run -d -p 80:80 -v /var/run/docker.sock:/tmp/docker.sock:ro nginxproxy/nginx-proxy
```
Then start any containers you want proxied with an env var `VIRTUAL_HOST=subdomain.youdomain.com`
$ docker run -e VIRTUAL_HOST=foo.bar.com ...
```console
docker run -e VIRTUAL_HOST=foo.bar.com ...
```
The containers being proxied must [expose](https://docs.docker.com/engine/reference/run/#expose-incoming-ports) the port to be proxied, either by using the `EXPOSE` directive in their `Dockerfile` or by using the `--expose` flag to `docker run` or `docker create` and be in the same network. By default, if you don't pass the --net flag when your nginx-proxy container is created, it will only be attached to the default bridge network. This means that it will not be able to connect to containers on networks other than bridge.
Provided your DNS is setup to forward foo.bar.com to the host running nginx-proxy, the request will be routed to a container with the VIRTUAL_HOST env var set.
Provided your DNS is setup to forward foo.bar.com to the host running nginx-proxy, the request will be routed to a container with the `VIRTUAL_HOST` env var set.
Note: providing a port number in `VIRTUAL_HOST` isn't suported, please see [virtual ports](https://github.com/nginx-proxy/nginx-proxy#virtual-ports) or [custom external HTTP/HTTPS ports](https://github.com/nginx-proxy/nginx-proxy#custom-external-httphttps-ports) depending on what you want to achieve.
### Image variants
@ -36,13 +44,17 @@ The nginx-proxy images are available in two flavors.
This image uses the debian:buster based nginx image.
$ docker pull nginxproxy/nginx-proxy:latest
```console
docker pull nginxproxy/nginx-proxy:latest
```
#### nginxproxy/nginx-proxy:alpine
This image is based on the nginx:alpine image. Use this image to fully support HTTP/2 (including ALPN required by recent Chrome versions). A valid certificate is required as well (see eg. below "SSL Support using letsencrypt" for more info).
This image is based on the nginx:alpine image. Use this image to fully support HTTP/2 (including ALPN required by recent Chrome versions). A valid certificate is required as well (see eg. below "SSL Support using an ACME CA" for more info).
$ docker pull nginxproxy/nginx-proxy:alpine
```console
docker pull nginxproxy/nginx-proxy:alpine
```
### Docker Compose
@ -59,13 +71,20 @@ services:
whoami:
image: jwilder/whoami
expose:
- "8000"
environment:
- VIRTUAL_HOST=whoami.local
- VIRTUAL_PORT=8000
```
```shell
$ docker-compose up
$ curl -H "Host: whoami.local" localhost
```console
docker-compose up
curl -H "Host: whoami.local" localhost
```
Example output:
```console
I'm 5b129ab83266
```
@ -73,22 +92,36 @@ I'm 5b129ab83266
You can activate the IPv6 support for the nginx-proxy container by passing the value `true` to the `ENABLE_IPV6` environment variable:
$ docker run -d -p 80:80 -e ENABLE_IPV6=true -v /var/run/docker.sock:/tmp/docker.sock:ro nginxproxy/nginx-proxy
```console
docker run -d -p 80:80 -e ENABLE_IPV6=true -v /var/run/docker.sock:/tmp/docker.sock:ro nginxproxy/nginx-proxy
```
### Multiple Ports
#### Scoped IPv6 Resolvers
If your container exposes multiple ports, nginx-proxy will default to the service running on port 80. If you need to specify a different port, you can set a VIRTUAL_PORT env var to select a different one. If your container only exposes one port and it has a VIRTUAL_HOST env var set, that port will be selected.
NginX does not support scoped IPv6 resolvers. In [docker-entrypoint.sh](./docker-entrypoint.sh) the resolvers are parsed from resolv.conf, but any scoped IPv6 addreses will be removed.
[1]: https://github.com/jwilder/docker-gen
[2]: http://jasonwilder.com/blog/2014/03/25/automated-nginx-reverse-proxy-for-docker/
#### IPv6 NAT
By default, docker uses IPv6-to-IPv4 NAT. This means all client connections from IPv6 addresses will show docker's internal IPv4 host address. To see true IPv6 client IP addresses, you must [enable IPv6](https://docs.docker.com/config/daemon/ipv6/) and use [ipv6nat](https://github.com/robbertkl/docker-ipv6nat). You must also disable the userland proxy by adding `"userland-proxy": false` to `/etc/docker/daemon.json` and restarting the daemon.
### Multiple Hosts
If you need to support multiple virtual hosts for a container, you can separate each entry with commas. For example, `foo.bar.com,baz.bar.com,bar.com` and each host will be setup the same.
### Virtual Ports
When your container exposes only one port, nginx-proxy will default to this port, else to port 80.
If you need to specify a different port, you can set a `VIRTUAL_PORT` env var to select a different one. This variable cannot be set to more than one port.
For each host defined into `VIRTUAL_HOST`, the associated virtual port is retrieved by order of precedence:
1. From the `VIRTUAL_PORT` environment variable
1. From the container's exposed port if there is only one
1. From the default port 80 when none of the above methods apply
### Wildcard Hosts
You can also use wildcards at the beginning and the end of host name, like `*.bar.com` or `foo.bar.*`. Or even a regular expression, which can be very useful in conjunction with a wildcard DNS service like [xip.io](http://xip.io), using `~^foo\.bar\..*\.xip\.io` will match `foo.bar.127.0.0.1.xip.io`, `foo.bar.10.0.2.2.xip.io` and all other given IPs. More information about this topic can be found in the nginx documentation about [`server_names`](http://nginx.org/en/docs/http/server_names.html).
You can also use wildcards at the beginning and the end of host name, like `*.bar.com` or `foo.bar.*`. Or even a regular expression, which can be very useful in conjunction with a wildcard DNS service like [nip.io](https://nip.io) or [sslip.io](https://sslip.io), using `~^foo\.bar\..*\.nip\.io` will match `foo.bar.127.0.0.1.nip.io`, `foo.bar.10.0.2.2.nip.io` and all other given IPs. More information about this topic can be found in the nginx documentation about [`server_names`](http://nginx.org/en/docs/http/server_names.html).
### Multiple Networks
@ -97,18 +130,26 @@ With the addition of [overlay networking](https://docs.docker.com/engine/usergui
If you want your `nginx-proxy` container to be attached to a different network, you must pass the `--net=my-network` option in your `docker create` or `docker run` command. At the time of this writing, only a single network can be specified at container creation time. To attach to other networks, you can use the `docker network connect` command after your container is created:
```console
$ docker run -d -p 80:80 -v /var/run/docker.sock:/tmp/docker.sock:ro \
docker run -d -p 80:80 -v /var/run/docker.sock:/tmp/docker.sock:ro \
--name my-nginx-proxy --net my-network nginxproxy/nginx-proxy
$ docker network connect my-other-network my-nginx-proxy
docker network connect my-other-network my-nginx-proxy
```
In this example, the `my-nginx-proxy` container will be connected to `my-network` and `my-other-network` and will be able to proxy to other containers attached to those networks.
### Custom external HTTP/HTTPS ports
If you want to use `nginx-proxy` with different external ports that the default ones of `80` for `HTTP` traffic and `443` for `HTTPS` traffic, you'll have to use the environment variable(s) `HTTP_PORT` and/or `HTTPS_PORT` in addition to the changes to the Docker port mapping. If you change the `HTTPS` port, the redirect for `HTTPS` traffic will also be configured to redirect to the custom port. Typical usage, here with the custom ports `1080` and `10443`:
```console
docker run -d -p 1080:1080 -p 10443:10443 -e HTTP_PORT=1080 -e HTTPS_PORT=10443 -v /var/run/docker.sock:/tmp/docker.sock:ro nginxproxy/nginx-proxy
```
### Internet vs. Local Network Access
If you allow traffic from the public internet to access your `nginx-proxy` container, you may want to restrict some containers to the internal network only, so they cannot be accessed from the public internet. On containers that should be restricted to the internal network, you should set the environment variable `NETWORK_ACCESS=internal`. By default, the *internal* network is defined as `127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16`. To change the list of networks considered internal, mount a file on the `nginx-proxy` at `/etc/nginx/network_internal.conf` with these contents, edited to suit your needs:
```
```Nginx
# These networks are considered "internal"
allow 127.0.0.0/8;
allow 10.0.0.0/8;
@ -119,7 +160,7 @@ allow 172.16.0.0/12;
deny all;
```
When internal-only access is enabled, external clients with be denied with an `HTTP 403 Forbidden`
When internal-only access is enabled, external clients will be denied with an `HTTP 403 Forbidden`
> If there is a load-balancer / reverse proxy in front of `nginx-proxy` that hides the client IP (example: AWS Application/Elastic Load Balancer), you will need to use the nginx `realip` module (already installed) to extract the client's IP from the HTTP request headers. Please see the [nginx realip module configuration](http://nginx.org/en/docs/http/ngx_http_realip_module.html) for more details. This configuration can be added to a new config file and mounted in `/etc/nginx/conf.d/`.
@ -131,15 +172,11 @@ If you would like the reverse proxy to connect to your backend using HTTPS inste
### uWSGI Backends
If you would like to connect to uWSGI backend, set `VIRTUAL_PROTO=uwsgi` on the
backend container. Your backend container should then listen on a port rather
than a socket and expose that port.
If you would like to connect to uWSGI backend, set `VIRTUAL_PROTO=uwsgi` on the backend container. Your backend container should then listen on a port rather than a socket and expose that port.
### FastCGI Backends
If you would like to connect to FastCGI backend, set `VIRTUAL_PROTO=fastcgi` on the
backend container. Your backend container should then listen on a port rather
than a socket and expose that port.
If you would like to connect to FastCGI backend, set `VIRTUAL_PROTO=fastcgi` on the backend container. Your backend container should then listen on a port rather than a socket and expose that port.
### FastCGI File Root Directory
@ -150,170 +187,134 @@ If you use fastcgi,you can set `VIRTUAL_ROOT=xxx` for your root directory
To set the default host for nginx use the env var `DEFAULT_HOST=foo.bar.com` for example
$ docker run -d -p 80:80 -e DEFAULT_HOST=foo.bar.com -v /var/run/docker.sock:/tmp/docker.sock:ro nginxproxy/nginx-proxy
```console
docker run -d -p 80:80 -e DEFAULT_HOST=foo.bar.com -v /var/run/docker.sock:/tmp/docker.sock:ro nginxproxy/nginx-proxy
```
nginx-proxy will then redirect all requests to a container where `VIRTUAL_HOST` is set to `DEFAULT_HOST`, if they don't match any (other) `VIRTUAL_HOST`. Using the example above requests without matching `VIRTUAL_HOST` will be redirected to a plain nginx instance after running the following command:
```console
docker run -d -e VIRTUAL_HOST=foo.bar.com nginx
```
### Separate Containers
nginx-proxy can also be run as two separate containers using the [jwilder/docker-gen](https://hub.docker.com/r/jwilder/docker-gen)
image and the official [nginx](https://registry.hub.docker.com/_/nginx/) image.
nginx-proxy can also be run as two separate containers using the [nginxproxy/docker-gen](https://hub.docker.com/r/nginxproxy/docker-gen) image and the official [nginx](https://registry.hub.docker.com/_/nginx/) image.
You may want to do this to prevent having the docker socket bound to a publicly exposed container service.
You can demo this pattern with docker-compose:
```console
$ docker-compose --file docker-compose-separate-containers.yml up
$ curl -H "Host: whoami.local" localhost
docker-compose --file docker-compose-separate-containers.yml up
curl -H "Host: whoami.local" localhost
```
Example output:
```console
I'm 5b129ab83266
```
To run nginx proxy as a separate container you'll need to have [nginx.tmpl](https://github.com/nginx-proxy/nginx-proxy/blob/master/nginx.tmpl) on your host system.
To run nginx proxy as a separate container you'll need to have [nginx.tmpl](https://github.com/nginx-proxy/nginx-proxy/blob/main/nginx.tmpl) on your host system.
First start nginx with a volume:
$ docker run -d -p 80:80 --name nginx -v /tmp/nginx:/etc/nginx/conf.d -t nginx
```console
docker run -d -p 80:80 --name nginx -v /tmp/nginx:/etc/nginx/conf.d -t nginx
```
Then start the docker-gen container with the shared volume and template:
```
$ docker run --volumes-from nginx \
```console
docker run --volumes-from nginx \
-v /var/run/docker.sock:/tmp/docker.sock:ro \
-v $(pwd):/etc/docker-gen/templates \
-t jwilder/docker-gen -notify-sighup nginx -watch /etc/docker-gen/templates/nginx.tmpl /etc/nginx/conf.d/default.conf
-t nginxproxy/docker-gen -notify-sighup nginx -watch /etc/docker-gen/templates/nginx.tmpl /etc/nginx/conf.d/default.conf
```
Finally, start your containers with `VIRTUAL_HOST` environment variables.
$ docker run -e VIRTUAL_HOST=foo.bar.com ...
### SSL Support using letsencrypt
```console
docker run -e VIRTUAL_HOST=foo.bar.com ...
```
[letsencrypt-nginx-proxy-companion](https://github.com/nginx-proxy/docker-letsencrypt-nginx-proxy-companion) is a lightweight companion container for the nginx-proxy. It allows the creation/renewal of Let's Encrypt certificates automatically.
### SSL Support using an ACME CA
Set `DHPARAM_GENERATION` environment variable to `false` to disabled Diffie-Hellman parameters completely. This will also ignore auto-generation made by `nginx-proxy`.
The default value is `true`
[acme-companion](https://github.com/nginx-proxy/acme-companion) is a lightweight companion container for the nginx-proxy. It allows the automated creation/renewal of SSL certificates using the ACME protocol.
$ docker run -e DHPARAM_GENERATION=false ....
### SSL Support
SSL is supported using single host, wildcard and SNI certificates using naming conventions for
certificates or optionally specifying a cert name (for SNI) as an environment variable.
SSL is supported using single host, wildcard and SNI certificates using naming conventions for certificates or optionally specifying a cert name (for SNI) as an environment variable.
To enable SSL:
$ docker run -d -p 80:80 -p 443:443 -v /path/to/certs:/etc/nginx/certs -v /var/run/docker.sock:/tmp/docker.sock:ro nginxproxy/nginx-proxy
```console
docker run -d -p 80:80 -p 443:443 -v /path/to/certs:/etc/nginx/certs -v /var/run/docker.sock:/tmp/docker.sock:ro nginxproxy/nginx-proxy
```
The contents of `/path/to/certs` should contain the certificates and private keys for any virtual
hosts in use. The certificate and keys should be named after the virtual host with a `.crt` and
`.key` extension. For example, a container with `VIRTUAL_HOST=foo.bar.com` should have a
`foo.bar.com.crt` and `foo.bar.com.key` file in the certs directory.
The contents of `/path/to/certs` should contain the certificates and private keys for any virtual hosts in use. The certificate and keys should be named after the virtual host with a `.crt` and `.key` extension. For example, a container with `VIRTUAL_HOST=foo.bar.com` should have a `foo.bar.com.crt` and `foo.bar.com.key` file in the certs directory.
If you are running the container in a virtualized environment (Hyper-V, VirtualBox, etc...),
/path/to/certs must exist in that environment or be made accessible to that environment.
By default, Docker is not able to mount directories on the host machine to containers running in a virtual machine.
If you are running the container in a virtualized environment (Hyper-V, VirtualBox, etc...), /path/to/certs must exist in that environment or be made accessible to that environment. By default, Docker is not able to mount directories on the host machine to containers running in a virtual machine.
#### Diffie-Hellman Groups
Diffie-Hellman groups are enabled by default, with a pregenerated key in `/etc/nginx/dhparam/dhparam.pem`.
You can mount a different `dhparam.pem` file at that location to override the default cert.
To use custom `dhparam.pem` files per-virtual-host, the files should be named after the virtual host with a
`dhparam` suffix and `.pem` extension. For example, a container with `VIRTUAL_HOST=foo.bar.com`
should have a `foo.bar.com.dhparam.pem` file in the `/etc/nginx/certs` directory.
[RFC7919 groups](https://datatracker.ietf.org/doc/html/rfc7919#appendix-A) with key lengths of 2048, 3072, and 4096 bits are [provided by `nginx-proxy`](https://github.com/nginx-proxy/nginx-proxy/dhparam). The ENV `DHPARAM_BITS` can be set to `2048` or `3072` to change from the default 4096-bit key. The DH key file will be located in the container at `/etc/nginx/dhparam/dhparam.pem`. Mounting a different `dhparam.pem` file at that location will override the RFC7919 key.
> NOTE: If you don't mount a `dhparam.pem` file at `/etc/nginx/dhparam/dhparam.pem`, one will be generated
at startup. Since it can take minutes to generate a new `dhparam.pem`, it is done at low priority in the
background. Once generation is complete, the `dhparam.pem` is saved on a persistent volume and nginx
is reloaded. This generation process only occurs the first time you start `nginx-proxy`.
To use custom `dhparam.pem` files per-virtual-host, the files should be named after the virtual host with a `dhparam` suffix and `.pem` extension. For example, a container with `VIRTUAL_HOST=foo.bar.com` should have a `foo.bar.com.dhparam.pem` file in the `/etc/nginx/certs` directory.
> COMPATIBILITY WARNING: The default generated `dhparam.pem` key is 4096 bits for A+ security. Some
> older clients (like Java 6 and 7) do not support DH keys with over 1024 bits. In order to support these
> clients, you must either provide your own `dhparam.pem`, or tell `nginx-proxy` to generate a 1024-bit
> key on startup by passing `-e DHPARAM_BITS=1024`.
> COMPATIBILITY WARNING: The default generated `dhparam.pem` key is 4096 bits for A+ security. Some older clients (like Java 6 and 7) do not support DH keys with over 1024 bits. In order to support these clients, you must provide your own `dhparam.pem`.
In the separate container setup, no pregenerated key will be available and neither the
[jwilder/docker-gen](https://hub.docker.com/r/jwilder/docker-gen) image nor the offical
[nginx](https://registry.hub.docker.com/_/nginx/) image will generate one. If you still want A+ security
in a separate container setup, you'll have to generate a 2048 or 4096 bits DH key file manually and mount it on the
nginx container, at `/etc/nginx/dhparam/dhparam.pem`.
In the separate container setup, no pre-generated key will be available and neither the [nginxproxy/docker-gen](https://hub.docker.com/r/nginxproxy/docker-gen) image, nor the offical [nginx](https://registry.hub.docker.com/_/nginx/) image will provide one. If you still want A+ security in a separate container setup, you should mount an RFC7919 DH key file to the nginx container at `/etc/nginx/dhparam/dhparam.pem`.
Set `DHPARAM_SKIP` environment variable to `true` to disable using default Diffie-Hellman parameters. The default value is `false`.
```console
docker run -e DHPARAM_SKIP=true ....
```
#### Wildcard Certificates
Wildcard certificates and keys should be named after the domain name with a `.crt` and `.key` extension.
For example `VIRTUAL_HOST=foo.bar.com` would use cert name `bar.com.crt` and `bar.com.key`.
Wildcard certificates and keys should be named after the domain name with a `.crt` and `.key` extension. For example `VIRTUAL_HOST=foo.bar.com` would use cert name `bar.com.crt` and `bar.com.key`.
#### SNI
If your certificate(s) supports multiple domain names, you can start a container with `CERT_NAME=<name>`
to identify the certificate to be used. For example, a certificate for `*.foo.com` and `*.bar.com`
could be named `shared.crt` and `shared.key`. A container running with `VIRTUAL_HOST=foo.bar.com`
and `CERT_NAME=shared` will then use this shared cert.
If your certificate(s) supports multiple domain names, you can start a container with `CERT_NAME=<name>` to identify the certificate to be used. For example, a certificate for `*.foo.com` and `*.bar.com` could be named `shared.crt` and `shared.key`. A container running with `VIRTUAL_HOST=foo.bar.com` and `CERT_NAME=shared` will then use this shared cert.
#### OCSP Stapling
To enable OCSP Stapling for a domain, `nginx-proxy` looks for a PEM certificate containing the trusted
CA certificate chain at `/etc/nginx/certs/<domain>.chain.pem`, where `<domain>` is the domain name in
the `VIRTUAL_HOST` directive. The format of this file is a concatenation of the public PEM CA
certificates starting with the intermediate CA most near the SSL certificate, down to the root CA. This is
often referred to as the "SSL Certificate Chain". If found, this filename is passed to the NGINX
[`ssl_trusted_certificate` directive](http://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_trusted_certificate)
and OCSP Stapling is enabled.
To enable OCSP Stapling for a domain, `nginx-proxy` looks for a PEM certificate containing the trusted CA certificate chain at `/etc/nginx/certs/<domain>.chain.pem`, where `<domain>` is the domain name in the `VIRTUAL_HOST` directive. The format of this file is a concatenation of the public PEM CA certificates starting with the intermediate CA most near the SSL certificate, down to the root CA. This is often referred to as the "SSL Certificate Chain". If found, this filename is passed to the NGINX [`ssl_trusted_certificate` directive](http://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_trusted_certificate) and OCSP Stapling is enabled.
#### How SSL Support Works
The default SSL cipher configuration is based on the [Mozilla intermediate profile](https://wiki.mozilla.org/Security/Server_Side_TLS#Intermediate_compatibility_.28recommended.29) version 5.0 which
should provide compatibility with clients back to Firefox 27, Android 4.4.2, Chrome 31, Edge, IE 11 on Windows 7,
Java 8u31, OpenSSL 1.0.1, Opera 20, and Safari 9. Note that the DES-based TLS ciphers were removed for security.
The configuration also enables HSTS, PFS, OCSP stapling and SSL session caches. Currently TLS 1.2 and 1.3
are supported.
The default SSL cipher configuration is based on the [Mozilla intermediate profile](https://wiki.mozilla.org/Security/Server_Side_TLS#Intermediate_compatibility_.28recommended.29) version 5.0 which should provide compatibility with clients back to Firefox 27, Android 4.4.2, Chrome 31, Edge, IE 11 on Windows 7, Java 8u31, OpenSSL 1.0.1, Opera 20, and Safari 9. Note that the DES-based TLS ciphers were removed for security. The configuration also enables HSTS, PFS, OCSP stapling and SSL session caches. Currently TLS 1.2 and 1.3 are supported.
If you don't require backward compatibility, you can use the [Mozilla modern profile](https://wiki.mozilla.org/Security/Server_Side_TLS#Modern_compatibility)
profile instead by including the environment variable `SSL_POLICY=Mozilla-Modern` to the nginx-proxy container or to your container.
This profile is compatible with clients back to Firefox 63, Android 10.0, Chrome 70, Edge 75, Java 11,
OpenSSL 1.1.1, Opera 57, and Safari 12.1. Note that this profile is **not** compatible with any version of Internet Explorer.
If you don't require backward compatibility, you can use the [Mozilla modern profile](https://wiki.mozilla.org/Security/Server_Side_TLS#Modern_compatibility) profile instead by including the environment variable `SSL_POLICY=Mozilla-Modern` to the nginx-proxy container or to your container. This profile is compatible with clients back to Firefox 63, Android 10.0, Chrome 70, Edge 75, Java 11, OpenSSL 1.1.1, Opera 57, and Safari 12.1. Note that this profile is **not** compatible with any version of Internet Explorer.
Other policies available through the `SSL_POLICY` environment variable are [`Mozilla-Old`](https://wiki.mozilla.org/Security/Server_Side_TLS#Old_backward_compatibility)
and the [AWS ELB Security Policies](https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-security-policy-table.html)
`AWS-TLS-1-2-2017-01`, `AWS-TLS-1-1-2017-01`, `AWS-2016-08`, `AWS-2015-05`, `AWS-2015-03` and `AWS-2015-02`.
Other policies available through the `SSL_POLICY` environment variable are [`Mozilla-Old`](https://wiki.mozilla.org/Security/Server_Side_TLS#Old_backward_compatibility) and the [AWS ELB Security Policies](https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-security-policy-table.html) `AWS-TLS-1-2-2017-01`, `AWS-TLS-1-1-2017-01`, `AWS-2016-08`, `AWS-2015-05`, `AWS-2015-03` and `AWS-2015-02`.
Note that the `Mozilla-Old` policy should use a 1024 bits DH key for compatibility but this container generates
a 4096 bits key. The [Diffie-Hellman Groups](#diffie-hellman-groups) section details different methods of bypassing
this, either globally or per virtual-host.
Note that the `Mozilla-Old` policy should use a 1024 bits DH key for compatibility but this container provides a 4096 bits key. The [Diffie-Hellman Groups](#diffie-hellman-groups) section details different methods of bypassing this, either globally or per virtual-host.
The default behavior for the proxy when port 80 and 443 are exposed is as follows:
* If a container has a usable cert, port 80 will redirect to 443 for that container so that HTTPS
is always preferred when available.
* If a container has a usable cert, port 80 will redirect to 443 for that container so that HTTPS is always preferred when available.
* If the container does not have a usable cert, a 503 will be returned.
Note that in the latter case, a browser may get an connection error as no certificate is available
to establish a connection. A self-signed or generic cert named `default.crt` and `default.key`
will allow a client browser to make a SSL connection (likely w/ a warning) and subsequently receive
a 500.
Note that in the latter case, a browser may get an connection error as no certificate is available to establish a connection. A self-signed or generic cert named `default.crt` and `default.key` will allow a client browser to make a SSL connection (likely w/ a warning) and subsequently receive a 500.
To serve traffic in both SSL and non-SSL modes without redirecting to SSL, you can include the
environment variable `HTTPS_METHOD=noredirect` (the default is `HTTPS_METHOD=redirect`). You can also
disable the non-SSL site entirely with `HTTPS_METHOD=nohttp`, or disable the HTTPS site with
`HTTPS_METHOD=nohttps`. `HTTPS_METHOD` can be specified on each container for which you want to
override the default behavior or on the proxy container to set it globally. If `HTTPS_METHOD=noredirect` is used, Strict Transport Security (HSTS)
is disabled to prevent HTTPS users from being redirected by the client. If you cannot get to the HTTP
site after changing this setting, your browser has probably cached the HSTS policy and is automatically
redirecting you back to HTTPS. You will need to clear your browser's HSTS cache or use an incognito
window / different browser.
To serve traffic in both SSL and non-SSL modes without redirecting to SSL, you can include the environment variable `HTTPS_METHOD=noredirect` (the default is `HTTPS_METHOD=redirect`). You can also disable the non-SSL site entirely with `HTTPS_METHOD=nohttp`, or disable the HTTPS site with `HTTPS_METHOD=nohttps`. `HTTPS_METHOD` can be specified on each container for which you want to override the default behavior or on the proxy container to set it globally. If `HTTPS_METHOD=noredirect` is used, Strict Transport Security (HSTS) is disabled to prevent HTTPS users from being redirected by the client. If you cannot get to the HTTP site after changing this setting, your browser has probably cached the HSTS policy and is automatically redirecting you back to HTTPS. You will need to clear your browser's HSTS cache or use an incognito window / different browser.
By default, [HTTP Strict Transport Security (HSTS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security)
is enabled with `max-age=31536000` for HTTPS sites. You can disable HSTS with the environment variable
`HSTS=off` or use a custom HSTS configuration like `HSTS=max-age=31536000; includeSubDomains; preload`.
*WARNING*: HSTS will force your users to visit the HTTPS version of your site for the `max-age` time -
even if they type in `http://` manually. The only way to get to an HTTP site after receiving an HSTS
response is to clear your browser's HSTS cache.
By default, [HTTP Strict Transport Security (HSTS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security) is enabled with `max-age=31536000` for HTTPS sites. You can disable HSTS with the environment variable `HSTS=off` or use a custom HSTS configuration like `HSTS=max-age=31536000; includeSubDomains; preload`.
*WARNING*: HSTS will force your users to visit the HTTPS version of your site for the `max-age` time - even if they type in `http://` manually. The only way to get to an HTTP site after receiving an HSTS response is to clear your browser's HSTS cache.
### Basic Authentication Support
In order to be able to secure your virtual host, you have to create a file named as its equivalent VIRTUAL_HOST variable on directory
/etc/nginx/htpasswd/$VIRTUAL_HOST
```
$ docker run -d -p 80:80 -p 443:443 \
```console
docker run -d -p 80:80 -p 443:443 \
-v /path/to/htpasswd:/etc/nginx/htpasswd \
-v /path/to/certs:/etc/nginx/certs \
-v /var/run/docker.sock:/tmp/docker.sock:ro \
@ -328,8 +329,7 @@ If you need to configure Nginx beyond what is possible using environment variabl
#### Replacing default proxy settings
If you want to replace the default proxy settings for the nginx container, add a configuration file at `/etc/nginx/proxy.conf`. A file with the default settings would
look like this:
If you want to replace the default proxy settings for the nginx container, add a configuration file at `/etc/nginx/proxy.conf`. A file with the default settings would look like this:
```Nginx
# HTTP 1.1 support
@ -368,7 +368,9 @@ RUN { \
Or it can be done by mounting in your custom configuration in your `docker run` command:
$ docker run -d -p 80:80 -p 443:443 -v /path/to/my_proxy.conf:/etc/nginx/conf.d/my_proxy.conf:ro -v /var/run/docker.sock:/tmp/docker.sock:ro nginxproxy/nginx-proxy
```console
docker run -d -p 80:80 -p 443:443 -v /path/to/my_proxy.conf:/etc/nginx/conf.d/my_proxy.conf:ro -v /var/run/docker.sock:/tmp/docker.sock:ro nginxproxy/nginx-proxy
```
#### Per-VIRTUAL_HOST
@ -378,38 +380,80 @@ In order to allow virtual hosts to be dynamically configured as backends are add
For example, if you have a virtual host named `app.example.com`, you could provide a custom configuration for that host as follows:
$ docker run -d -p 80:80 -p 443:443 -v /path/to/vhost.d:/etc/nginx/vhost.d:ro -v /var/run/docker.sock:/tmp/docker.sock:ro nginxproxy/nginx-proxy
$ { echo 'server_tokens off;'; echo 'client_max_body_size 100m;'; } > /path/to/vhost.d/app.example.com
```console
docker run -d -p 80:80 -p 443:443 -v /path/to/vhost.d:/etc/nginx/vhost.d:ro -v /var/run/docker.sock:/tmp/docker.sock:ro nginxproxy/nginx-proxy
{ echo 'server_tokens off;'; echo 'client_max_body_size 100m;'; } > /path/to/vhost.d/app.example.com
```
If you are using multiple hostnames for a single container (e.g. `VIRTUAL_HOST=example.com,www.example.com`), the virtual host configuration file must exist for each hostname. If you would like to use the same configuration for multiple virtual host names, you can use a symlink:
$ { echo 'server_tokens off;'; echo 'client_max_body_size 100m;'; } > /path/to/vhost.d/www.example.com
$ ln -s /path/to/vhost.d/www.example.com /path/to/vhost.d/example.com
```console
{ echo 'server_tokens off;'; echo 'client_max_body_size 100m;'; } > /path/to/vhost.d/www.example.com
ln -s /path/to/vhost.d/www.example.com /path/to/vhost.d/example.com
```
#### Per-VIRTUAL_HOST default configuration
If you want most of your virtual hosts to use a default single configuration and then override on a few specific ones, add those settings to the `/etc/nginx/vhost.d/default` file. This file
will be used on any virtual host which does not have a `/etc/nginx/vhost.d/{VIRTUAL_HOST}` file associated with it.
If you want most of your virtual hosts to use a default single configuration and then override on a few specific ones, add those settings to the `/etc/nginx/vhost.d/default` file. This file will be used on any virtual host which does not have a `/etc/nginx/vhost.d/{VIRTUAL_HOST}` file associated with it.
#### Per-VIRTUAL_HOST location configuration
To add settings to the "location" block on a per-`VIRTUAL_HOST` basis, add your configuration file under `/etc/nginx/vhost.d`
just like the previous section except with the suffix `_location`.
To add settings to the "location" block on a per-`VIRTUAL_HOST` basis, add your configuration file under `/etc/nginx/vhost.d` just like the previous section except with the suffix `_location`.
For example, if you have a virtual host named `app.example.com` and you have configured a proxy_cache `my-cache` in another custom file, you could tell it to use a proxy cache as follows:
$ docker run -d -p 80:80 -p 443:443 -v /path/to/vhost.d:/etc/nginx/vhost.d:ro -v /var/run/docker.sock:/tmp/docker.sock:ro nginxproxy/nginx-proxy
$ { echo 'proxy_cache my-cache;'; echo 'proxy_cache_valid 200 302 60m;'; echo 'proxy_cache_valid 404 1m;' } > /path/to/vhost.d/app.example.com_location
```console
docker run -d -p 80:80 -p 443:443 -v /path/to/vhost.d:/etc/nginx/vhost.d:ro -v /var/run/docker.sock:/tmp/docker.sock:ro nginxproxy/nginx-proxy
{ echo 'proxy_cache my-cache;'; echo 'proxy_cache_valid 200 302 60m;'; echo 'proxy_cache_valid 404 1m;' } > /path/to/vhost.d/app.example.com_location
```
If you are using multiple hostnames for a single container (e.g. `VIRTUAL_HOST=example.com,www.example.com`), the virtual host configuration file must exist for each hostname. If you would like to use the same configuration for multiple virtual host names, you can use a symlink:
$ { echo 'proxy_cache my-cache;'; echo 'proxy_cache_valid 200 302 60m;'; echo 'proxy_cache_valid 404 1m;' } > /path/to/vhost.d/app.example.com_location
$ ln -s /path/to/vhost.d/www.example.com /path/to/vhost.d/example.com
```console
{ echo 'proxy_cache my-cache;'; echo 'proxy_cache_valid 200 302 60m;'; echo 'proxy_cache_valid 404 1m;' } > /path/to/vhost.d/app.example.com_location
ln -s /path/to/vhost.d/www.example.com /path/to/vhost.d/example.com
```
#### Per-VIRTUAL_HOST location default configuration
If you want most of your virtual hosts to use a default single `location` block configuration and then override on a few specific ones, add those settings to the `/etc/nginx/vhost.d/default_location` file. This file
will be used on any virtual host which does not have a `/etc/nginx/vhost.d/{VIRTUAL_HOST}_location` file associated with it.
If you want most of your virtual hosts to use a default single `location` block configuration and then override on a few specific ones, add those settings to the `/etc/nginx/vhost.d/default_location` file. This file will be used on any virtual host which does not have a `/etc/nginx/vhost.d/{VIRTUAL_HOST}_location` file associated with it.
#### Per-VIRTUAL_HOST `server_tokens` configuration
Per virtual-host `servers_tokens` directive can be configured by passing appropriate value to the `SERVER_TOKENS` environment variable. Please see the [nginx http_core module configuration](https://nginx.org/en/docs/http/ngx_http_core_module.html#server_tokens) for more details.
### Unhashed vs SHA1 upstream names
By default the nginx configuration `upstream` blocks will use this block's corresponding hostname as a predictable name. However, this can cause issues in some setups (see [this issue](https://github.com/nginx-proxy/nginx-proxy/issues/1162)). In those cases you might want to switch to SHA1 names for the `upstream` blocks by setting the `SHA1_UPSTREAM_NAME` environment variable to `true` on the nginx-proxy container.
Please note that using regular expressions in `VIRTUAL_HOST` will always result in a corresponding `upstream` block with an SHA1 name.
### Troubleshooting
In case you can't access your VIRTUAL_HOST, set `DEBUG=true` in the client container's environment and have a look at the generated nginx configuration file `/etc/nginx/conf.d/default.conf`:
```console
docker exec <nginx-proxy-instance> cat /etc/nginx/conf.d/default.conf
```
Especially at `upstream` definition blocks which should look like:
```Nginx
# foo.example.com
upstream foo.example.com {
## Can be connected with "my_network" network
# Exposed ports: [{ <exposed_port1> tcp } { <exposed_port2> tcp } ...]
# Default virtual port: <exposed_port|80>
# VIRTUAL_PORT: <VIRTUAL_PORT>
# foo
server 172.18.0.9:<Port>;
# Fallback entry
server 127.0.0.1 down;
}
```
The effective `Port` is retrieved by order of precedence:
1. From the `VIRTUAL_PORT` environment variable
1. From the container's exposed port if there is only one
1. From the default port 80 when none of the above methods apply
### Contributing
@ -417,22 +461,19 @@ Before submitting pull requests or issues, please check github to make sure an e
#### Running Tests Locally
To run tests, you need to prepare the docker image to test which must be tagged `nginxproxy/nginx-proxy:test`:
To run tests, you just need to run the command below:
docker build -t nginxproxy/nginx-proxy:test . # build the Debian variant image
```console
make test
```
and call the [test/pytest.sh](test/pytest.sh) script.
This commands run tests on two variants of the nginx-proxy docker image: Debian and Alpine.
Then build the Alpine variant of the image:
docker build -f Dockerfile.alpine -t nginxproxy/nginx-proxy:test . # build the Alpline variant image
and call the [test/pytest.sh](test/pytest.sh) script again.
If your system has the `make` command, you can automate those tasks by calling:
make test
You can run the tests for each of these images with their respective commands:
```console
make test-debian
make test-alpine
```
You can learn more about how the test suite works and how to write new tests in the [test/README.md](test/README.md) file.

View file

@ -1,8 +0,0 @@
-----BEGIN DH PARAMETERS-----
MIIBCAKCAQEAzB2nIGzpVq7afJnKBm1X0d64avwOlP2oneiKwxRHdDI/5+6TpH1P
F8ipodGuZBUMmupoB3D34pu2Qq5boNW983sm18ww9LMz2i/pxhSdB+mYAew+A6h6
ltQ5pNtyn4NaKw1SDFkqvde3GNPhaWoPDbZDJhpHGblR3w1b/ag+lTLZUvVwcD8L
jYS9f9YWAC6T7WxAxh4zvu1Z0I1EKde8KYBxrreZNheXpXHqMNyJYZCaY2Hb/4oI
EL65qZq1GCWezpWMjhk6pOnV5gbvqfhoazCv/4OdRv6RoWOIYBNs9BmGho4AtXqV
FYLdYDhOvN4aVs9Ir+G8ouwiRnix24+UewIBAg==
-----END DH PARAMETERS-----

8
dhparam/ffdhe2048.pem Normal file
View file

@ -0,0 +1,8 @@
-----BEGIN DH PARAMETERS-----
MIIBCAKCAQEA//////////+t+FRYortKmq/cViAnPTzx2LnFg84tNpWp4TZBFGQz
+8yTnc4kmz75fS/jY2MMddj2gbICrsRhetPfHtXV/WVhJDP1H18GbtCFY2VVPe0a
87VXE15/V8k1mE8McODmi3fipona8+/och3xWKE2rec1MKzKT0g6eXq8CrGCsyT7
YdEIqUuyyOP7uWrat2DX9GgdT0Kj3jlN9K5W7edjcrsZCwenyO4KbXCeAvzhzffi
7MA0BM0oNC9hkXL+nOmFg/+OTxIy7vKBg8P+OxtMb61zO7X8vC7CIAXFjvGDfRaD
ssbzSibBsu/6iGtCOGEoXJf//////////wIBAg==
-----END DH PARAMETERS-----

11
dhparam/ffdhe3072.pem Normal file
View file

@ -0,0 +1,11 @@
-----BEGIN DH PARAMETERS-----
MIIBiAKCAYEA//////////+t+FRYortKmq/cViAnPTzx2LnFg84tNpWp4TZBFGQz
+8yTnc4kmz75fS/jY2MMddj2gbICrsRhetPfHtXV/WVhJDP1H18GbtCFY2VVPe0a
87VXE15/V8k1mE8McODmi3fipona8+/och3xWKE2rec1MKzKT0g6eXq8CrGCsyT7
YdEIqUuyyOP7uWrat2DX9GgdT0Kj3jlN9K5W7edjcrsZCwenyO4KbXCeAvzhzffi
7MA0BM0oNC9hkXL+nOmFg/+OTxIy7vKBg8P+OxtMb61zO7X8vC7CIAXFjvGDfRaD
ssbzSibBsu/6iGtCOGEfz9zeNVs7ZRkDW7w09N75nAI4YbRvydbmyQd62R0mkff3
7lmMsPrBhtkcrv4TCYUTknC0EwyTvEN5RPT9RFLi103TZPLiHnH1S/9croKrnJ32
nuhtK8UiNjoNq8Uhl5sN6todv5pC1cRITgq80Gv6U93vPBsg7j/VnXwl5B0rZsYu
N///////////AgEC
-----END DH PARAMETERS-----

13
dhparam/ffdhe4096.pem Normal file
View file

@ -0,0 +1,13 @@
-----BEGIN DH PARAMETERS-----
MIICCAKCAgEA//////////+t+FRYortKmq/cViAnPTzx2LnFg84tNpWp4TZBFGQz
+8yTnc4kmz75fS/jY2MMddj2gbICrsRhetPfHtXV/WVhJDP1H18GbtCFY2VVPe0a
87VXE15/V8k1mE8McODmi3fipona8+/och3xWKE2rec1MKzKT0g6eXq8CrGCsyT7
YdEIqUuyyOP7uWrat2DX9GgdT0Kj3jlN9K5W7edjcrsZCwenyO4KbXCeAvzhzffi
7MA0BM0oNC9hkXL+nOmFg/+OTxIy7vKBg8P+OxtMb61zO7X8vC7CIAXFjvGDfRaD
ssbzSibBsu/6iGtCOGEfz9zeNVs7ZRkDW7w09N75nAI4YbRvydbmyQd62R0mkff3
7lmMsPrBhtkcrv4TCYUTknC0EwyTvEN5RPT9RFLi103TZPLiHnH1S/9croKrnJ32
nuhtK8UiNjoNq8Uhl5sN6todv5pC1cRITgq80Gv6U93vPBsg7j/VnXwl5B0rZp4e
8W5vUsMWTfT7eTDp5OWIV7asfV9C1p9tGHdjzx1VA0AEh/VbpX4xzHpxNciG77Qx
iu1qHgEtnmgyqQdgCpGBMMRtx3j5ca0AOAkpmaMzy4t6Gh25PXFAADwqTs6p+Y0K
zAqCkc3OyX3Pjsm1Wn+IpGtNtahR9EGC4caKAH5eZV9q//////////8CAQI=
-----END DH PARAMETERS-----

View file

@ -9,8 +9,9 @@ services:
- /etc/nginx/conf.d
dockergen:
image: jwilder/docker-gen
command: -notify-sighup nginx -watch /etc/docker-gen/templates/nginx.tmpl /etc/nginx/conf.d/default.conf
image: nginxproxy/docker-gen
command: -notify-sighup nginx -watch /etc/docker-gen/templates/nginx.tmpl
/etc/nginx/conf.d/default.conf
volumes_from:
- nginx
volumes:

View file

@ -1,34 +1,114 @@
#!/bin/bash
set -e
# Warn if the DOCKER_HOST socket does not exist
if [[ $DOCKER_HOST = unix://* ]]; then
socket_file=${DOCKER_HOST#unix://}
if ! [ -S $socket_file ]; then
cat >&2 <<-EOT
ERROR: you need to share your Docker host socket with a volume at $socket_file
Typically you should run your nginxproxy/nginx-proxy with: \`-v /var/run/docker.sock:$socket_file:ro\`
See the documentation at http://git.io/vZaGJ
EOT
socketMissing=1
function _parse_true() {
case "$1" in
true | True | TRUE | 1)
return 0
;;
*)
return 1
;;
esac
}
function _parse_false() {
case "$1" in
false | False | FALSE | 0)
return 0
;;
*)
return 1
;;
esac
}
function _print_version {
if [[ -n "${NGINX_PROXY_VERSION:-}" ]]; then
echo "Info: running nginx-proxy version ${NGINX_PROXY_VERSION}"
fi
}
function _check_unix_socket() {
# Warn if the DOCKER_HOST socket does not exist
if [[ ${DOCKER_HOST} == unix://* ]]; then
local SOCKET_FILE="${DOCKER_HOST#unix://}"
if [[ ! -S ${SOCKET_FILE} ]]; then
cat >&2 <<-EOT
ERROR: you need to share your Docker host socket with a volume at ${SOCKET_FILE}
Typically you should run your nginxproxy/nginx-proxy with: \`-v /var/run/docker.sock:${SOCKET_FILE}:ro\`
See the documentation at: https://github.com/nginx-proxy/nginx-proxy/#usage
EOT
exit 1
fi
fi
fi
}
# Generate dhparam file if required
# Note: if $DHPARAM_BITS is not defined, generate-dhparam.sh will use 4096 as a default
# Note2: if $DHPARAM_GENERATION is set to false in environment variable, dh param generator will skip completely
/app/generate-dhparam.sh $DHPARAM_BITS $DHPARAM_GENERATION
function _resolvers() {
# Compute the DNS resolvers for use in the templates - if the IP contains ":", it's IPv6 and must be enclosed in []
RESOLVERS=$(awk '$1 == "nameserver" {print ($2 ~ ":")? "["$2"]": $2}' ORS=' ' /etc/resolv.conf | sed 's/ *$//g'); export RESOLVERS
# Compute the DNS resolvers for use in the templates - if the IP contains ":", it's IPv6 and must be enclosed in []
export RESOLVERS=$(awk '$1 == "nameserver" {print ($2 ~ ":")? "["$2"]": $2}' ORS=' ' /etc/resolv.conf | sed 's/ *$//g')
if [ "x$RESOLVERS" = "x" ]; then
echo "Warning: unable to determine DNS resolvers for nginx" >&2
unset RESOLVERS
fi
SCOPED_IPV6_REGEX='\[fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}\]'
# If the user has run the default command and the socket doesn't exist, fail
if [ "$socketMissing" = 1 -a "$1" = forego -a "$2" = start -a "$3" = '-r' ]; then
exit 1
if [[ -z ${RESOLVERS} ]]; then
echo 'Warning: unable to determine DNS resolvers for nginx' >&2
unset RESOLVERS
elif [[ ${RESOLVERS} =~ ${SCOPED_IPV6_REGEX} ]]; then
echo -n 'Warning: Scoped IPv6 addresses removed from resolvers: ' >&2
echo "${RESOLVERS}" | grep -Eo "$SCOPED_IPV6_REGEX" | paste -s -d ' ' >&2
RESOLVERS=$(echo "${RESOLVERS}" | sed -r "s/${SCOPED_IPV6_REGEX}//g" | xargs echo -n); export RESOLVERS
fi
}
function _setup_dhparam() {
# DH params will be supplied for nginx here:
local DHPARAM_FILE='/etc/nginx/dhparam/dhparam.pem'
# Should be 2048, 3072, or 4096 (default):
local FFDHE_GROUP="${DHPARAM_BITS:=4096}"
# DH params may be provided by the user (rarely necessary)
if [[ -f ${DHPARAM_FILE} ]]; then
echo 'Warning: A custom dhparam.pem file was provided. Best practice is to use standardized RFC7919 DHE groups instead.' >&2
return 0
elif _parse_true "${DHPARAM_SKIP:=false}"; then
echo 'Skipping Diffie-Hellman parameters setup.'
return 0
elif _parse_false "${DHPARAM_GENERATION:=true}"; then
echo 'Warning: The DHPARAM_GENERATION environment variable is deprecated, please consider using DHPARAM_SKIP set to true instead.' >&2
echo 'Skipping Diffie-Hellman parameters setup.'
return 0
elif [[ ! ${DHPARAM_BITS} =~ ^(2048|3072|4096)$ ]]; then
echo "ERROR: Unsupported DHPARAM_BITS size: ${DHPARAM_BITS}. Use: 2048, 3072, or 4096 (default)." >&2
exit 1
fi
echo 'Setting up DH Parameters..'
# Use an existing pre-generated DH group from RFC7919 (https://datatracker.ietf.org/doc/html/rfc7919#appendix-A):
local RFC7919_DHPARAM_FILE="/app/dhparam/ffdhe${FFDHE_GROUP}.pem"
# Provide the DH params file to nginx:
cp "${RFC7919_DHPARAM_FILE}" "${DHPARAM_FILE}"
}
# Run the init logic if the default CMD was provided
if [[ $* == 'forego start -r' ]]; then
_print_version
_check_unix_socket
_resolvers
_setup_dhparam
fi
exec "$@"

View file

@ -1,52 +0,0 @@
#!/bin/bash -e
# The first argument is the bit depth of the dhparam, or 4096 if unspecified
DHPARAM_BITS=${1:-4096}
GENERATE_DHPARAM=${2:-true}
# If a dhparam file is not available, use the pre-generated one and generate a new one in the background.
# Note that /etc/nginx/dhparam is a volume, so this dhparam will persist restarts.
PREGEN_DHPARAM_FILE="/app/dhparam.pem.default"
DHPARAM_FILE="/etc/nginx/dhparam/dhparam.pem"
GEN_LOCKFILE="/tmp/dhparam_generating.lock"
# The hash of the pregenerated dhparam file is used to check if the pregen dhparam is already in use
PREGEN_HASH=$(md5sum $PREGEN_DHPARAM_FILE | cut -d" " -f1)
if [[ -f $DHPARAM_FILE ]]; then
CURRENT_HASH=$(md5sum $DHPARAM_FILE | cut -d" " -f1)
if [[ $PREGEN_HASH != $CURRENT_HASH ]]; then
# There is already a dhparam, and it's not the default
echo "Custom dhparam.pem file found, generation skipped"
exit 0
fi
if [[ -f $GEN_LOCKFILE ]]; then
# Generation is already in progress
exit 0
fi
fi
if [[ $GENERATE_DHPARAM =~ ^[Ff][Aa][Ll][Ss][Ee]$ ]]; then
echo "Skipping Diffie-Hellman parameters generation and Ignoring pre-generated dhparam.pem"
exit 0
fi
cat >&2 <<-EOT
WARNING: $DHPARAM_FILE was not found. A pre-generated dhparam.pem will be used for now while a new one
is being generated in the background. Once the new dhparam.pem is in place, nginx will be reloaded.
EOT
# Put the default dhparam file in place so we can start immediately
cp $PREGEN_DHPARAM_FILE $DHPARAM_FILE
touch $GEN_LOCKFILE
# Generate a new dhparam in the background in a low priority and reload nginx when finished (grep removes the progress indicator).
(
(
nice -n +5 openssl dhparam -dsaparam -out $DHPARAM_FILE.tmp $DHPARAM_BITS 2>&1 \
&& mv $DHPARAM_FILE.tmp $DHPARAM_FILE \
&& echo "dhparam generation complete, reloading nginx" \
&& nginx -s reload
) | grep -vE '^[\.+]+'
rm $GEN_LOCKFILE
) &disown

View file

@ -1,29 +1,10 @@
{{ $CurrentContainer := where $ "ID" .Docker.CurrentContainerID | first }}
{{ $nginx_proxy_version := coalesce $.Env.NGINX_PROXY_VERSION "" }}
{{ $external_http_port := coalesce $.Env.HTTP_PORT "80" }}
{{ $external_https_port := coalesce $.Env.HTTPS_PORT "443" }}
{{ define "upstream" }}
{{ if .Address }}
{{/* If we got the containers from swarm and this container's port is published to host, use host IP:PORT */}}
{{ if and .Container.Node.ID .Address.HostPort }}
# {{ .Container.Node.Name }}/{{ .Container.Name }}
server {{ .Container.Node.Address.IP }}:{{ .Address.HostPort }};
{{/* If there is no swarm node or the port is not published on host, use container's IP:PORT */}}
{{ else if .Network }}
# {{ .Container.Name }}
server {{ .Network.IP }}:{{ .Address.Port }};
{{ end }}
{{ else if .Network }}
# {{ .Container.Name }}
{{ if .Network.IP }}
server {{ .Network.IP }} down;
{{ else }}
server 127.0.0.1 down;
{{ end }}
{{ end }}
{{ end }}
{{ $debug_all := $.Env.DEBUG }}
{{ $sha1_upstream_name := parseBool (coalesce $.Env.SHA1_UPSTREAM_NAME "false") }}
{{ define "ssl_policy" }}
{{ if eq .ssl_policy "Mozilla-Modern" }}
@ -68,6 +49,10 @@
{{ end }}
{{ end }}
{{ if ne $nginx_proxy_version "" }}
# nginx-proxy version : {{ $nginx_proxy_version }}
{{ end }}
# If we receive X-Forwarded-Proto, pass it through; otherwise, pass along the
# scheme used to connect to this server
map $http_x_forwarded_proto $proxy_x_forwarded_proto {
@ -97,8 +82,8 @@ server_names_hash_bucket_size 128;
ssl_dhparam /etc/nginx/dhparam/dhparam.pem;
{{ end }}
# Set appropriate X-Forwarded-Ssl header
map $scheme $proxy_x_forwarded_ssl {
# Set appropriate X-Forwarded-Ssl header based on $proxy_x_forwarded_proto
map $proxy_x_forwarded_proto $proxy_x_forwarded_ssl {
default off;
https on;
}
@ -107,7 +92,8 @@ gzip_types text/plain text/css application/javascript application/json applicati
log_format vhost '$host $remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
'"$http_referer" "$http_user_agent" '
'"$upstream_addr"';
access_log off;
@ -143,6 +129,7 @@ proxy_set_header Proxy "";
{{ $enable_ipv6 := eq (or ($.Env.ENABLE_IPV6) "") "true" }}
server {
server_name _; # This is just an invalid value which will never trigger on a real hostname.
server_tokens off;
listen {{ $external_http_port }};
{{ if $enable_ipv6 }}
listen [::]:{{ $external_http_port }};
@ -154,6 +141,7 @@ server {
{{ if (and (exists "/etc/nginx/certs/default.crt") (exists "/etc/nginx/certs/default.key")) }}
server {
server_name _; # This is just an invalid value which will never trigger on a real hostname.
server_tokens off;
listen {{ $external_https_port }} ssl http2;
{{ if $enable_ipv6 }}
listen [::]:{{ $external_https_port }} ssl http2;
@ -172,36 +160,62 @@ server {
{{ $host := trim $host }}
{{ $is_regexp := hasPrefix "~" $host }}
{{ $upstream_name := when $is_regexp (sha1 $host) $host }}
{{ $upstream_name := when (or $is_regexp $sha1_upstream_name) (sha1 $host) $host }}
# {{ $host }}
upstream {{ $upstream_name }} {
{{ $server_found := "false" }}
{{ range $container := $containers }}
{{ $addrLen := len $container.Addresses }}
{{ $debug := (eq (coalesce $container.Env.DEBUG $debug_all "false") "true") }}
{{/* If only 1 port exposed, use that as a default, else 80 */}}
{{ $defaultPort := (when (eq (len $container.Addresses) 1) (first $container.Addresses) (dict "Port" "80")).Port }}
{{ $port := (coalesce $container.Env.VIRTUAL_PORT $defaultPort) }}
{{ $address := where $container.Addresses "Port" $port | first }}
{{ if $debug }}
# Exposed ports: {{ $container.Addresses }}
# Default virtual port: {{ $defaultPort }}
# VIRTUAL_PORT: {{ $container.Env.VIRTUAL_PORT }}
{{ if not $address }}
# /!\ Virtual port not exposed
{{ end }}
{{ end }}
{{ range $knownNetwork := $CurrentContainer.Networks }}
{{ range $containerNetwork := $container.Networks }}
{{ if (and (ne $containerNetwork.Name "ingress") (or (eq $knownNetwork.Name $containerNetwork.Name) (eq $knownNetwork.Name "host"))) }}
## Can be connected with "{{ $containerNetwork.Name }}" network
{{/* If only 1 port exposed, use that */}}
{{ if eq $addrLen 1 }}
{{ $address := index $container.Addresses 0 }}
{{ template "upstream" (dict "Container" $container "Address" $address "Network" $containerNetwork) }}
{{/* If more than one port exposed, use the one matching VIRTUAL_PORT env var, falling back to standard web port 80 */}}
{{ else }}
{{ $port := coalesce $container.Env.VIRTUAL_PORT "80" }}
{{ $address := where $container.Addresses "Port" $port | first }}
{{ template "upstream" (dict "Container" $container "Address" $address "Network" $containerNetwork) }}
## Can be connected with "{{ $containerNetwork.Name }}" network
{{ if $address }}
{{/* If we got the containers from swarm and this container's port is published to host, use host IP:PORT */}}
{{ if and $container.Node.ID $address.HostPort }}
{{ $server_found = "true" }}
# {{ $container.Node.Name }}/{{ $container.Name }}
server {{ $container.Node.Address.IP }}:{{ $address.HostPort }};
{{/* If there is no swarm node or the port is not published on host, use container's IP:PORT */}}
{{ else if $containerNetwork }}
{{ $server_found = "true" }}
# {{ $container.Name }}
server {{ $containerNetwork.IP }}:{{ $address.Port }};
{{ end }}
{{ else if $containerNetwork }}
# {{ $container.Name }}
{{ if $containerNetwork.IP }}
{{ $server_found = "true" }}
server {{ $containerNetwork.IP }}:{{ $port }};
{{ else }}
# /!\ No IP for this network!
{{ end }}
{{ end }}
{{ else }}
# Cannot connect to network of this container
server 127.0.0.1 down;
# Cannot connect to network '{{ $containerNetwork.Name }}' of this container
{{ end }}
{{ end }}
{{ end }}
{{ end }}
{{/* nginx-proxy/nginx-proxy#1105 */}}
{{ if (eq $server_found "false") }}
# Fallback entry
server 127.0.0.1 down;
{{ end }}
}
{{ $default_host := or ($.Env.DEFAULT_HOST) "" }}
@ -210,6 +224,9 @@ upstream {{ $upstream_name }} {
{{/* Get the VIRTUAL_PROTO defined by containers w/ the same vhost, falling back to "http" */}}
{{ $proto := trim (or (first (groupByKeys $containers "Env.VIRTUAL_PROTO")) "http") }}
{{/* Get the SERVER_TOKENS defined by containers w/ the same vhost, falling back to "" */}}
{{ $server_tokens := trim (or (first (groupByKeys $containers "Env.SERVER_TOKENS")) "") }}
{{/* Get the NETWORK_ACCESS defined by containers w/ the same vhost, falling back to "external" */}}
{{ $network_tag := or (first (groupByKeys $containers "Env.NETWORK_ACCESS")) "external" }}
@ -246,6 +263,9 @@ upstream {{ $upstream_name }} {
{{ if eq $https_method "redirect" }}
server {
server_name {{ $host }};
{{ if $server_tokens }}
server_tokens {{ $server_tokens }};
{{ end }}
listen {{ $external_http_port }} {{ $default_server }};
{{ if $enable_ipv6 }}
listen [::]:{{ $external_http_port }} {{ $default_server }};
@ -274,6 +294,9 @@ server {
server {
server_name {{ $host }};
{{ if $server_tokens }}
server_tokens {{ $server_tokens }};
{{ end }}
listen {{ $external_https_port }} ssl http2 {{ $default_server }};
{{ if $enable_ipv6 }}
listen [::]:{{ $external_https_port }} ssl http2 {{ $default_server }};
@ -350,6 +373,9 @@ server {
server {
server_name {{ $host }};
{{ if $server_tokens }}
server_tokens {{ $server_tokens }};
{{ end }}
listen {{ $external_http_port }} {{ $default_server }};
{{ if $enable_ipv6 }}
listen [::]:80 {{ $default_server }};
@ -399,6 +425,9 @@ server {
{{ if (and (not $is_https) (exists "/etc/nginx/certs/default.crt") (exists "/etc/nginx/certs/default.key")) }}
server {
server_name {{ $host }};
{{ if $server_tokens }}
server_tokens {{ $server_tokens }};
{{ end }}
listen {{ $external_https_port }} ssl http2 {{ $default_server }};
{{ if $enable_ipv6 }}
listen [::]:{{ $external_https_port }} ssl http2 {{ $default_server }};

View file

@ -4,25 +4,20 @@ Nginx proxy test suite
Install requirements
--------------------
You need [python 2.7](https://www.python.org/) and [pip](https://pip.pypa.io/en/stable/installing/) installed. Then run the commands:
You need [python 3.9](https://www.python.org/) and [pip](https://pip.pypa.io/en/stable/installing/) installed. Then run the commands:
requirements/build.sh
pip install -r requirements/python-requirements.txt
If you can't install those requirements on your computer, you can alternatively use the _pytest.sh_ script which will run the tests from a Docker container which has those requirements.
Prepare the nginx-proxy test image
----------------------------------
docker build -t nginxproxy/nginx-proxy:test ..
make build-nginx-proxy-test-debian
or if you want to test the alpine flavor:
docker build -t nginxproxy/nginx-proxy:test -f Dockerfile.alpine ..
make sure to tag that test image exactly `nginxproxy/nginx-proxy:test` or the test suite won't work.
make build-nginx-proxy-test-alpine
Run the test suite
------------------
@ -43,7 +38,7 @@ Run one single test module
Write a test module
-------------------
This test suite uses [pytest](http://doc.pytest.org/en/latest/). The [conftest.py](conftest.py) file will be automatically loaded by pytest and will provide you with two useful pytest [fixtures](http://doc.pytest.org/en/latest/fixture.html#fixture):
This test suite uses [pytest](http://doc.pytest.org/en/latest/). The [conftest.py](conftest.py) file will be automatically loaded by pytest and will provide you with two useful pytest [fixtures](https://docs.pytest.org/en/latest/explanation/fixtures.html):
- docker_compose
- nginxproxy
@ -61,7 +56,7 @@ The fixture will run the _docker-compose_ command with the `-f` option to load t
In the case you are running pytest from within a docker container, the `docker_compose` fixture will make sure the container running pytest is attached to all docker networks. That way, your test will be able to reach any of them.
In your tests, you can use the `docker_compose` variable to query and command the docker daemon as it provides you with a [client from the docker python module](https://docker-py.readthedocs.io/en/2.0.2/client.html#client-reference).
In your tests, you can use the `docker_compose` variable to query and command the docker daemon as it provides you with a [client from the docker python module](https://docker-py.readthedocs.io/en/4.4.4/client.html#client-reference).
Also this fixture alters the way the python interpreter resolves domain names to IP addresses in the following ways:
@ -99,8 +94,7 @@ Furthermore, the nginxproxy methods accept an additional keyword parameter: `ipv
### The web docker image
When you ran the `requirements/build.sh` script earlier, you built a [`web`](requirements/README.md) docker image which is convenient for running a small web server in a container. This image can produce containers that listens on multiple ports at the same time.
When you run the `make build-webserver` command, you built a [`web`](requirements/README.md) docker image which is convenient for running a small web server in a container. This image can produce containers that listens on multiple ports at the same time.
### Testing TLS

View file

@ -24,7 +24,7 @@ fi
# Create a nginx container (which conveniently provides the `openssl` command)
###############################################################################
CONTAINER=$(docker run -d -v $DIR:/work -w /work -e SAN="$ALTERNATE_DOMAINS" nginx:1.14.1)
CONTAINER=$(docker run -d -v $DIR:/work -w /work -e SAN="$ALTERNATE_DOMAINS" nginx:1.19.10)
# Configure openssl
docker exec $CONTAINER bash -c '
apt-get update && apt-get install openssl

View file

@ -1,18 +1,20 @@
from __future__ import print_function
import contextlib
import logging
import os
import re
import shlex
import socket
import subprocess
import time
import re
from typing import List
import backoff
import docker
import pytest
import requests
from _pytest._code.code import ReprExceptionInfo
from distutils.version import LooseVersion
from docker.models.containers import Container
from requests.packages.urllib3.util.connection import HAS_IPV6
logging.basicConfig(level=logging.INFO)
@ -21,12 +23,15 @@ logging.getLogger('DNS').setLevel(logging.DEBUG)
logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.WARN)
CA_ROOT_CERTIFICATE = os.path.join(os.path.dirname(__file__), 'certs/ca-root.crt')
I_AM_RUNNING_INSIDE_A_DOCKER_CONTAINER = os.path.isfile("/.dockerenv")
PYTEST_RUNNING_IN_CONTAINER = os.environ.get('PYTEST_RUNNING_IN_CONTAINER') == "1"
FORCE_CONTAINER_IPV6 = False # ugly global state to consider containers' IPv6 address instead of IPv4
docker_client = docker.from_env()
# Name of pytest container to reference if it's being used for running tests
test_container = 'nginx-proxy-pytest'
###############################################################################
#
@ -64,17 +69,32 @@ class requests_for_docker(object):
if os.path.isfile(CA_ROOT_CERTIFICATE):
self.session.verify = CA_ROOT_CERTIFICATE
def get_conf(self):
@staticmethod
def get_nginx_proxy_containers() -> List[Container]:
"""
Return the nginx config file
Return list of containers
"""
nginx_proxy_containers = docker_client.containers.list(filters={"ancestor": "nginxproxy/nginx-proxy:test"})
if len(nginx_proxy_containers) > 1:
pytest.fail("Too many running nginxproxy/nginx-proxy:test containers", pytrace=False)
elif len(nginx_proxy_containers) == 0:
pytest.fail("No running nginxproxy/nginx-proxy:test container", pytrace=False)
return nginx_proxy_containers
def get_conf(self):
"""
Return the nginx config file
"""
nginx_proxy_containers = self.get_nginx_proxy_containers()
return get_nginx_conf_from_container(nginx_proxy_containers[0])
def get_ip(self) -> str:
"""
Return the nginx container ip address
"""
nginx_proxy_containers = self.get_nginx_proxy_containers()
return container_ip(nginx_proxy_containers[0])
def get(self, *args, **kwargs):
with ipv6(kwargs.pop('ipv6', False)):
@backoff.on_predicate(backoff.constant, lambda r: r.status_code in (404, 502), interval=.3, max_tries=30, jitter=None)
@ -121,7 +141,7 @@ class requests_for_docker(object):
return getattr(requests, name)
def container_ip(container):
def container_ip(container: Container):
"""
return the IP address of a container.
@ -133,7 +153,7 @@ def container_ip(container):
pytest.skip("This system does not support IPv6")
ip = container_ipv6(container)
if ip == '':
pytest.skip("Container %s has no IPv6 address" % container.name)
pytest.skip(f"Container {container.name} has no IPv6 address")
else:
return ip
else:
@ -142,7 +162,7 @@ def container_ip(container):
return net_info["bridge"]["IPAddress"]
# not default bridge network, fallback on first network defined
network_name = net_info.keys()[0]
network_name = list(net_info.keys())[0]
return net_info[network_name]["IPAddress"]
@ -155,7 +175,7 @@ def container_ipv6(container):
return net_info["bridge"]["GlobalIPv6Address"]
# not default bridge network, fallback on first network defined
network_name = net_info.keys()[0]
network_name = list(net_info.keys())[0]
return net_info[network_name]["GlobalIPv6Address"]
@ -167,15 +187,15 @@ def nginx_proxy_dns_resolver(domain_name):
:return: IP or None
"""
log = logging.getLogger('DNS')
log.debug("nginx_proxy_dns_resolver(%r)" % domain_name)
log.debug(f"nginx_proxy_dns_resolver({domain_name!r})")
if 'nginx-proxy' in domain_name:
nginxproxy_containers = docker_client.containers.list(filters={"status": "running", "ancestor": "nginxproxy/nginx-proxy:test"})
if len(nginxproxy_containers) == 0:
log.warn("no container found from image nginxproxy/nginx-proxy:test while resolving %r", domain_name)
log.warn(f"no container found from image nginxproxy/nginx-proxy:test while resolving {domain_name!r}")
return
nginxproxy_container = nginxproxy_containers[0]
ip = container_ip(nginxproxy_container)
log.info("resolving domain name %r as IP address %s of nginx-proxy container %s" % (domain_name, ip, nginxproxy_container.name))
log.info(f"resolving domain name {domain_name!r} as IP address {ip} of nginx-proxy container {nginxproxy_container.name}")
return ip
def docker_container_dns_resolver(domain_name):
@ -186,24 +206,24 @@ def docker_container_dns_resolver(domain_name):
:return: IP or None
"""
log = logging.getLogger('DNS')
log.debug("docker_container_dns_resolver(%r)" % domain_name)
log.debug(f"docker_container_dns_resolver({domain_name!r})")
match = re.search('(^|.+\.)(?P<container>[^.]+)\.container\.docker$', domain_name)
match = re.search(r'(^|.+\.)(?P<container>[^.]+)\.container\.docker$', domain_name)
if not match:
log.debug("%r does not match" % domain_name)
log.debug(f"{domain_name!r} does not match")
return
container_name = match.group('container')
log.debug("looking for container %r" % container_name)
log.debug(f"looking for container {container_name!r}")
try:
container = docker_client.containers.get(container_name)
except docker.errors.NotFound:
log.warn("container named %r not found while resolving %r" % (container_name, domain_name))
log.warn(f"container named {container_name!r} not found while resolving {domain_name!r}")
return
log.debug("container %r found (%s)" % (container.name, container.short_id))
log.debug(f"container {container.name!r} found ({container.short_id})")
ip = container_ip(container)
log.info("resolving domain name %r as IP address %s of container %s" % (domain_name, ip, container.name))
log.info(f"resolving domain name {domain_name!r} as IP address {ip} of container {container.name}")
return ip
@ -216,9 +236,14 @@ def monkey_patch_urllib_dns_resolver():
prv_getaddrinfo = socket.getaddrinfo
dns_cache = {}
def new_getaddrinfo(*args):
logging.getLogger('DNS').debug("resolving domain name %s" % repr(args))
logging.getLogger('DNS').debug(f"resolving domain name {repr(args)}")
_args = list(args)
# Fail early when querying IP directly and it is forced ipv6 when not supported,
# Otherwise a pytest container not using the host network fails to pass `test_raw-ip-vhost`.
if FORCE_CONTAINER_IPV6 and not HAS_IPV6:
pytest.skip("This system does not support IPv6")
# custom DNS resolvers
ip = nginx_proxy_dns_resolver(args[0])
if ip is None:
@ -242,9 +267,9 @@ def restore_urllib_dns_resolver(getaddrinfo_func):
def remove_all_containers():
for container in docker_client.containers.list(all=True):
if I_AM_RUNNING_INSIDE_A_DOCKER_CONTAINER and container.id.startswith(socket.gethostname()):
if PYTEST_RUNNING_IN_CONTAINER and container.name == test_container:
continue # pytest is running within a Docker container, so we do not want to remove that particular container
logging.info("removing container %s" % container.name)
logging.info(f"removing container {container.name}")
container.remove(v=True, force=True)
@ -253,27 +278,30 @@ def get_nginx_conf_from_container(container):
return the nginx /etc/nginx/conf.d/default.conf file content from a container
"""
import tarfile
from cStringIO import StringIO
strm, stat = container.get_archive('/etc/nginx/conf.d/default.conf')
with tarfile.open(fileobj=StringIO(strm.read())) as tf:
from io import BytesIO
strm_generator, stat = container.get_archive('/etc/nginx/conf.d/default.conf')
strm_fileobj = BytesIO(b"".join(strm_generator))
with tarfile.open(fileobj=strm_fileobj) as tf:
conffile = tf.extractfile('default.conf')
return conffile.read()
def docker_compose_up(compose_file='docker-compose.yml'):
logging.info('docker-compose -f %s up -d' % compose_file)
logging.info(f'docker-compose -f {compose_file} up -d')
try:
subprocess.check_output(shlex.split('docker-compose -f %s up -d' % compose_file), stderr=subprocess.STDOUT)
except subprocess.CalledProcessError, e:
pytest.fail("Error while runninng 'docker-compose -f %s up -d':\n%s" % (compose_file, e.output), pytrace=False)
subprocess.check_output(shlex.split(f'docker-compose -f {compose_file} up -d'), stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
pytest.fail(f"Error while runninng 'docker-compose -f {compose_file} up -d':\n{e.output}", pytrace=False)
def docker_compose_down(compose_file='docker-compose.yml'):
logging.info('docker-compose -f %s down' % compose_file)
logging.info(f'docker-compose -f {compose_file} down -v')
try:
subprocess.check_output(shlex.split('docker-compose -f %s down' % compose_file), stderr=subprocess.STDOUT)
except subprocess.CalledProcessError, e:
pytest.fail("Error while runninng 'docker-compose -f %s down':\n%s" % (compose_file, e.output), pytrace=False)
subprocess.check_output(shlex.split(f'docker-compose -f {compose_file} down -v'), stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
pytest.fail(f"Error while runninng 'docker-compose -f {compose_file} down -v':\n{e.output}", pytrace=False)
def wait_for_nginxproxy_to_be_ready():
@ -286,7 +314,7 @@ def wait_for_nginxproxy_to_be_ready():
return
container = containers[0]
for line in container.logs(stream=True):
if "Watching docker events" in line:
if b"Watching docker events" in line:
logging.debug("nginx-proxy ready")
break
@ -307,7 +335,7 @@ def find_docker_compose_file(request):
if docker_compose_file_module_variable is not None:
docker_compose_file = os.path.join( test_module_dir, docker_compose_file_module_variable)
if not os.path.isfile(docker_compose_file):
raise ValueError("docker compose file %r could not be found. Check your test module `docker_compose_file` variable value." % docker_compose_file)
raise ValueError(f"docker compose file {docker_compose_file!r} could not be found. Check your test module `docker_compose_file` variable value.")
else:
if os.path.isfile(yml_file):
docker_compose_file = yml_file
@ -319,7 +347,7 @@ def find_docker_compose_file(request):
if not os.path.isfile(docker_compose_file):
logging.error("Could not find any docker-compose file named either '{0}.yml', '{0}.yaml' or 'docker-compose.yml'".format(request.module.__name__))
logging.debug("using docker compose file %s" % docker_compose_file)
logging.debug(f"using docker compose file {docker_compose_file}")
return docker_compose_file
@ -329,19 +357,24 @@ def connect_to_network(network):
:return: the name of the network we were connected to, or None
"""
if I_AM_RUNNING_INSIDE_A_DOCKER_CONTAINER:
if PYTEST_RUNNING_IN_CONTAINER:
try:
my_container = docker_client.containers.get(socket.gethostname())
my_container = docker_client.containers.get(test_container)
except docker.errors.NotFound:
logging.warn("container %r not found" % socket.gethostname())
logging.warn(f"container {test_container} not found")
return
# figure out our container networks
my_networks = my_container.attrs["NetworkSettings"]["Networks"].keys()
my_networks = list(my_container.attrs["NetworkSettings"]["Networks"].keys())
# make sure our container is connected to the nginx-proxy's network
if network not in my_networks:
logging.info("Connecting to docker network: %s" % network.name)
# If the pytest container is using host networking, it cannot connect to container networks (not required with host network)
if 'host' in my_networks:
return None
# Make sure our container is connected to the nginx-proxy's network,
# but avoid connecting to `none` network (not valid) with `test_server-down` tests
if network.name not in my_networks and network.name != 'none':
logging.info(f"Connecting to docker network: {network.name}")
network.connect(my_container)
return network
@ -352,19 +385,19 @@ def disconnect_from_network(network=None):
:param network: name of a docker network to disconnect from
"""
if I_AM_RUNNING_INSIDE_A_DOCKER_CONTAINER and network is not None:
if PYTEST_RUNNING_IN_CONTAINER and network is not None:
try:
my_container = docker_client.containers.get(socket.gethostname())
my_container = docker_client.containers.get(test_container)
except docker.errors.NotFound:
logging.warn("container %r not found" % socket.gethostname())
logging.warn(f"container {test_container} not found")
return
# figure out our container networks
my_networks_names = my_container.attrs["NetworkSettings"]["Networks"].keys()
my_networks_names = list(my_container.attrs["NetworkSettings"]["Networks"].keys())
# disconnect our container from the given network
if network.name in my_networks_names:
logging.info("Disconnecting from network %s" % network.name)
logging.info(f"Disconnecting from network {network.name}")
network.disconnect(my_container)
@ -374,11 +407,11 @@ def connect_to_all_networks():
:return: a list of networks we connected to
"""
if not I_AM_RUNNING_INSIDE_A_DOCKER_CONTAINER:
if not PYTEST_RUNNING_IN_CONTAINER:
return []
else:
# find the list of docker networks
networks = filter(lambda network: len(network.containers) > 0 and network.name != 'bridge', docker_client.networks.list())
networks = [network for network in docker_client.networks.list(greedy=True) if len(network.containers) > 0 and network.name != 'bridge']
return [connect_to_network(network) for network in networks]
@ -388,7 +421,7 @@ def connect_to_all_networks():
#
###############################################################################
@pytest.yield_fixture(scope="module")
@pytest.fixture(scope="module")
def docker_compose(request):
"""
pytest fixture providing containers described in a docker compose file. After the tests, remove the created containers
@ -412,7 +445,7 @@ def docker_compose(request):
restore_urllib_dns_resolver(original_dns_resolver)
@pytest.yield_fixture()
@pytest.fixture()
def nginxproxy():
"""
Provides the `nginxproxy` object that can be used in the same way the requests module is:
@ -456,7 +489,7 @@ def pytest_runtest_makereport(item, call):
def pytest_runtest_setup(item):
previousfailed = getattr(item.parent, "_previousfailed", None)
if previousfailed is not None:
pytest.xfail("previous test failed (%s)" % previousfailed.name)
pytest.xfail(f"previous test failed ({previousfailed.name})")
###############################################################################
#
@ -469,5 +502,5 @@ try:
except docker.errors.ImageNotFound:
pytest.exit("The docker image 'nginxproxy/nginx-proxy:test' is missing")
if docker.__version__ != "2.1.0":
pytest.exit("This test suite is meant to work with the python docker module v2.1.0")
if LooseVersion(docker.__version__) < LooseVersion("5.0.0"):
pytest.exit("This test suite is meant to work with the python docker module v5.0.0 or later")

View file

@ -1,8 +0,0 @@
-----BEGIN DH PARAMETERS-----
MIIBCAKCAQEA1cae6HqPSgicEuAuSCf6Ii3d6qMX9Ta8lnwoX0JQ0CWK7mzaiiIi
dY7oHmc4cq0S3SH+g0tdLP9yqygFS9hdUGINwS2VV6poj2/vdL/dUshegyxpEH58
nofCPnFDeKkcPDMYAlGS8zjp60TsBkRJKcrxxwnjod1Q5mWuMN5KH3sxs842udKH
0nHFE9kKW/NfXb+EGsjpocGpf786cGuCO2d00THsoItOEcM9/aI8DX1QcyxAHR6D
HaYTFJnyyx8Q44u27M15idI4pbNoKORlotiuOwCTGYCfbN14aOV+Ict7aSF8FWpP
48j9SMNuIu2DlF9pNLo6fsrOjYY3c9X12wIBAg==
-----END DH PARAMETERS-----

View file

@ -1,3 +1,5 @@
[pytest]
# disable the creation of the `.cache` folders
addopts = -p no:cacheprovider --ignore=requirements --ignore=certs -r s -v
markers =
incremental: mark a test as incremental.

View file

@ -8,12 +8,13 @@
# #
###############################################################################
# Returns the absolute directory path to this script
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
ARGS="$@"
ARGS=("$@")
# check requirements
echo "> Building nginx-proxy-tester image..."
docker build -t nginx-proxy-tester -f $DIR/requirements/Dockerfile-nginx-proxy-tester $DIR/requirements
docker build -t nginx-proxy-tester -f "${DIR}/requirements/Dockerfile-nginx-proxy-tester" "${DIR}/requirements"
# run the nginx-proxy-tester container setting the correct value for the working dir in order for
# docker-compose to work properly when run from within that container.

View file

@ -1,7 +1,6 @@
FROM python:2.7-alpine
FROM python:3.9
# Note: we're using alpine because it has openssl 1.0.2, which we need for testing
RUN apk add --update bash openssl curl && rm -rf /var/cache/apk/*
ENV PYTEST_RUNNING_IN_CONTAINER=1
COPY python-requirements.txt /requirements.txt
RUN pip install -r /requirements.txt

View file

@ -2,7 +2,7 @@ This directory contains resources to build Docker images tests depend on
# Build images
./build.sh
make build-webserver
# python-requirements.txt

View file

@ -1,6 +0,0 @@
#!/bin/bash
set -e
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
docker build -t web $DIR/web

View file

@ -1,5 +1,5 @@
backoff==1.3.2
docker-compose==1.11.2
docker==2.1.0
pytest==3.0.5
requests==2.11.1
backoff==1.11.1
docker-compose==1.29.2
docker==5.0.3
pytest==7.0.1
requests==2.27.1

View file

@ -13,13 +13,13 @@ class Handler(http.server.SimpleHTTPRequestHandler):
if self.path == "/headers":
response_body += self.headers.as_string()
elif self.path == "/port":
response_body += "answer from port %s\n" % PORT
response_body += f"answer from port {PORT}\n"
elif re.match("/status/(\d+)", self.path):
result = re.match("/status/(\d+)", self.path)
response_code = int(result.group(1))
response_body += "answer with response code %s\n" % response_code
response_body += f"answer with response code {response_code}\n"
elif self.path == "/":
response_body += "I'm %s\n" % os.environ['HOSTNAME']
response_body += f"I'm {os.environ['HOSTNAME']}\n"
else:
response_body += "No route for this path!\n"
response_code = 404

View file

@ -11,8 +11,7 @@ script_dir = os.path.dirname(__file__)
pytestmark = pytest.mark.xfail() # TODO delete this marker once those issues are fixed
@pytest.yield_fixture(scope="module", autouse=True)
@pytest.fixture(scope="module", autouse=True)
def certs():
"""
pytest fixture that provides cert and key files into the tmp_certs directory
@ -43,7 +42,7 @@ def test_http_web_is_301(docker_compose, nginxproxy):
def test_https_web_is_200(docker_compose, nginxproxy):
r = nginxproxy.get("https://web.nginx-proxy/port")
assert r.status_code == 200
assert 'answer from port 81\n' in r.text
assert "answer from port 81\n" in r.text
@pytest.mark.incremental

View file

@ -3,8 +3,6 @@ from time import sleep
import pytest
import requests
pytestmark = pytest.mark.xfail() # TODO delete this marker once #585 is merged
def test_default_nginx_welcome_page_should_not_be_served(docker_compose, nginxproxy):
r = nginxproxy.get("http://whatever.nginx-proxy/", allow_redirects=False)

View file

@ -19,6 +19,5 @@ sut:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/f00.sock:ro
- ./lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro
environment:
DOCKER_HOST: unix:///f00.sock

View file

@ -4,7 +4,6 @@ services:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- ./lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro
web:
image: web

View file

@ -2,7 +2,6 @@ nginx-proxy:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- ../lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro
- ./my_custom_proxy_settings.conf:/etc/nginx/vhost.d/default_location:ro
- ./my_custom_proxy_settings_bar.conf:/etc/nginx/vhost.d/web3.nginx-proxy.local_location:ro

View file

@ -4,7 +4,6 @@ services:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- ../lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro
- ./my_custom_proxy_settings.conf:/etc/nginx/proxy.conf:ro
web1:

View file

@ -19,4 +19,4 @@ def test_custom_conf_does_not_apply_to_web2(docker_compose, nginxproxy):
assert "X-test" not in r.headers
def test_custom_block_is_present_in_nginx_generated_conf(docker_compose, nginxproxy):
assert "include /etc/nginx/vhost.d/web1.nginx-proxy.local_location;" in nginxproxy.get_conf()
assert b"include /etc/nginx/vhost.d/web1.nginx-proxy.local_location;" in nginxproxy.get_conf()

View file

@ -4,7 +4,6 @@ services:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- ../lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro
- ./my_custom_proxy_settings.conf:/etc/nginx/vhost.d/web1.nginx-proxy.local_location:ro
web1:

View file

@ -4,7 +4,6 @@ services:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- ../lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro
- ./my_custom_proxy_settings.conf:/etc/nginx/vhost.d/web1.nginx-proxy.local:ro
web1:

View file

@ -4,7 +4,6 @@ services:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- ../lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro
- ./my_custom_proxy_settings.conf:/etc/nginx/conf.d/my_custom_proxy_settings.conf:ro
web1:

View file

@ -0,0 +1,12 @@
import pytest
import re
def test_debug_info_is_present_in_nginx_generated_conf(docker_compose, nginxproxy):
conf = nginxproxy.get_conf().decode('ASCII')
assert re.search(r"# Exposed ports: \[\{\d+\.\d+\.\d+\.\d+\s+80\s+tcp \} \{\d+\.\d+\.\d+\.\d+\s+81\s+tcp \}\]", conf) or \
re.search(r"# Exposed ports: \[\{\d+\.\d+\.\d+\.\d+\s+81\s+tcp \} \{\d+\.\d+\.\d+\.\d+\s+80\s+tcp \}\]", conf)
assert re.search(r"# Exposed ports: \[\{\d+\.\d+\.\d+\.\d+\s+82\s+tcp \} \{\d+\.\d+\.\d+\.\d+\s+83\s+tcp \}\]", conf) or \
re.search(r"# Exposed ports: \[\{\d+\.\d+\.\d+\.\d+\s+83\s+tcp \} \{\d+\.\d+\.\d+\.\d+\s+82\s+tcp \}\]", conf)
assert "# Default virtual port: 80" in conf
assert "# VIRTUAL_PORT: 82" in conf
assert conf.count("# /!\\ Virtual port not exposed") == 1

View file

@ -0,0 +1,26 @@
web1:
image: web
expose:
- "80"
- "81"
environment:
WEB_PORTS: "80 81"
VIRTUAL_HOST: "web1.nginx-proxy.tld"
VIRTUAL_PORT: "82"
web2:
image: web
expose:
- "82"
- "83"
environment:
WEB_PORTS: "82 83"
VIRTUAL_HOST: "web2.nginx-proxy.tld"
VIRTUAL_PORT: "82"
sut:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
environment:
DEBUG: "true"

View file

@ -0,0 +1,8 @@
import pytest
import re
def test_debug_info_is_present_in_nginx_generated_conf(docker_compose, nginxproxy):
conf = nginxproxy.get_conf().decode('ASCII')
assert re.search(r"# Exposed ports: \[\{\d+\.\d+\.\d+\.\d+\s+80\s+tcp \} \{\d+\.\d+\.\d+\.\d+\s+81\s+tcp \}\]", conf) or \
re.search(r"# Exposed ports: \[\{\d+\.\d+\.\d+\.\d+\s+81\s+tcp \} \{\d+\.\d+\.\d+\.\d+\s+80\s+tcp \}\]", conf)
assert conf.count("# Exposed ports: [{") == 1

View file

@ -0,0 +1,25 @@
web1:
image: web
expose:
- "80"
- "81"
environment:
WEB_PORTS: "80 81"
VIRTUAL_HOST: "web1.nginx-proxy.tld"
VIRTUAL_PORT: "82"
DEBUG: "true"
web2:
image: web
expose:
- "82"
- "83"
environment:
WEB_PORTS: "82 83"
VIRTUAL_HOST: "web2.nginx-proxy.tld"
VIRTUAL_PORT: "82"
sut:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro

View file

@ -13,6 +13,5 @@ sut:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- ./lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro
environment:
DEFAULT_HOST: web1.tld

View file

@ -4,7 +4,7 @@ import logging
import pytest
@pytest.yield_fixture(scope="module")
@pytest.fixture(scope="module")
def nginx_tmpl():
"""
pytest fixture which extracts the the nginx config template from
@ -13,14 +13,18 @@ def nginx_tmpl():
script_dir = os.path.dirname(__file__)
logging.info("extracting nginx.tmpl from nginxproxy/nginx-proxy:test")
docker_client = docker.from_env()
print(docker_client.containers.run(
image='nginxproxy/nginx-proxy:test',
remove=True,
volumes=['{current_dir}:{current_dir}'.format(current_dir=script_dir)],
entrypoint='sh',
command='-xc "cp /app/nginx.tmpl {current_dir} && chmod 777 {current_dir}/nginx.tmpl"'.format(
current_dir=script_dir),
stderr=True))
print(
docker_client.containers.run(
image="nginxproxy/nginx-proxy:test",
remove=True,
volumes=["{current_dir}:{current_dir}".format(current_dir=script_dir)],
entrypoint="sh",
command='-xc "cp /app/nginx.tmpl {current_dir} && chmod 777 {current_dir}/nginx.tmpl"'.format(
current_dir=script_dir
),
stderr=True,
)
)
yield
logging.info("removing nginx.tmpl")
os.remove(os.path.join(script_dir, "nginx.tmpl"))
@ -35,4 +39,4 @@ def test_forwards_to_whoami(nginx_tmpl, docker_compose, nginxproxy):
r = nginxproxy.get("http://whoami.nginx.container.docker/")
assert r.status_code == 200
whoami_container = docker_compose.containers.get("whoami")
assert r.text == "I'm %s\n" % whoami_container.id[:12]
assert r.text == f"I'm {whoami_container.id[:12]}\n"

View file

@ -6,10 +6,9 @@ services:
container_name: nginx
volumes:
- /etc/nginx/conf.d
- ../lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro
dockergen:
image: jwilder/docker-gen
image: nginxproxy/docker-gen
command: -notify-sighup nginx -watch /etc/docker-gen/templates/nginx.tmpl /etc/nginx/conf.d/default.conf
volumes_from:
- nginx

View file

@ -3,31 +3,17 @@ import docker
import logging
import pytest
import re
def versiontuple(v):
"""
>>> versiontuple("1.12.3")
(1, 12, 3)
>>> versiontuple("1.13.0")
(1, 13, 0)
>>> versiontuple("17.03.0-ce")
(17, 3, 0)
>>> versiontuple("17.03.0-ce") < (1, 13)
False
"""
return tuple(map(int, (v.split('-')[0].split("."))))
from distutils.version import LooseVersion
raw_version = docker.from_env().version()['Version']
raw_version = docker.from_env().version()["Version"]
pytestmark = pytest.mark.skipif(
versiontuple(raw_version) < (1, 13),
reason="Docker compose syntax v3 requires docker engine v1.13 or later (got %s)" % raw_version)
LooseVersion(raw_version) < LooseVersion("1.13"),
reason="Docker compose syntax v3 requires docker engine v1.13 or later (got {raw_version})"
)
@pytest.yield_fixture(scope="module")
@pytest.fixture(scope="module")
def nginx_tmpl():
"""
pytest fixture which extracts the the nginx config template from
@ -36,14 +22,18 @@ def nginx_tmpl():
script_dir = os.path.dirname(__file__)
logging.info("extracting nginx.tmpl from nginxproxy/nginx-proxy:test")
docker_client = docker.from_env()
print(docker_client.containers.run(
image='nginxproxy/nginx-proxy:test',
remove=True,
volumes=['{current_dir}:{current_dir}'.format(current_dir=script_dir)],
entrypoint='sh',
command='-xc "cp /app/nginx.tmpl {current_dir} && chmod 777 {current_dir}/nginx.tmpl"'.format(
current_dir=script_dir),
stderr=True))
print(
docker_client.containers.run(
image="nginxproxy/nginx-proxy:test",
remove=True,
volumes=["{current_dir}:{current_dir}".format(current_dir=script_dir)],
entrypoint="sh",
command='-xc "cp /app/nginx.tmpl {current_dir} && chmod 777 {current_dir}/nginx.tmpl"'.format(
current_dir=script_dir
),
stderr=True,
)
)
yield
logging.info("removing nginx.tmpl")
os.remove(os.path.join(script_dir, "nginx.tmpl"))
@ -58,9 +48,9 @@ def test_forwards_to_whoami(nginx_tmpl, docker_compose, nginxproxy):
r = nginxproxy.get("http://whoami.nginx.container.docker/")
assert r.status_code == 200
whoami_container = docker_compose.containers.get("whoami")
assert r.text == "I'm %s\n" % whoami_container.id[:12]
assert r.text == f"I'm {whoami_container.id[:12]}\n"
if __name__ == '__main__':
if __name__ == "__main__":
import doctest
doctest.testmod()

View file

@ -5,10 +5,9 @@ services:
container_name: nginx
volumes:
- nginx_conf:/etc/nginx/conf.d
- ../lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro
dockergen:
image: jwilder/docker-gen
image: nginxproxy/docker-gen
command: -notify-sighup nginx -watch /etc/docker-gen/templates/nginx.tmpl /etc/nginx/conf.d/default.conf
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro

View file

@ -7,7 +7,7 @@ import pytest
from docker.errors import NotFound
@pytest.yield_fixture()
@pytest.fixture()
def web1(docker_compose):
"""
pytest fixture creating a web container with `VIRTUAL_HOST=web1.nginx-proxy` listening on port 81.

View file

@ -2,4 +2,3 @@ nginxproxy:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- ./lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro

View file

@ -0,0 +1,71 @@
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 4096 (0x1000)
Signature Algorithm: sha256WithRSAEncryption
Issuer: O=nginx-proxy test suite, CN=www.nginx-proxy.tld
Validity
Not Before: May 11 18:25:49 2021 GMT
Not After : Sep 26 18:25:49 2048 GMT
Subject: CN=web-server-tokens-off.nginx-proxy.tld
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
RSA Public-Key: (2048 bit)
Modulus:
00:b4:fa:9d:8a:74:3f:17:ea:99:1c:45:71:18:90:
eb:92:35:38:d7:90:21:81:0a:91:05:41:cf:b5:87:
34:bd:d8:7b:7f:7d:06:33:f8:94:67:8e:e4:07:54:
7f:b7:62:c5:76:6c:7f:7c:19:25:19:2c:36:9a:26:
54:8e:2d:97:02:78:31:c6:13:d3:ad:f3:31:62:e6:
cf:96:ae:63:37:dd:bd:73:cb:4e:fb:3f:9b:65:67:
97:d8:5a:5d:0e:72:b1:11:ab:0e:d7:23:a9:b7:22:
de:23:74:7e:88:7c:28:98:a9:6e:00:f4:be:8c:69:
ea:3f:33:8b:19:97:da:1b:a6:65:b5:5a:92:01:3c:
3a:13:6b:00:02:e1:98:78:d3:da:ea:a6:9c:33:b0:
1d:9f:02:c4:f1:d0:d6:de:7a:f7:42:12:4b:31:fb:
ed:e9:d7:d8:15:e8:4e:18:91:7c:9d:bf:0f:b0:12:
d6:e2:80:8b:7a:ef:17:70:51:f4:3c:b7:43:cb:56:
61:af:61:7a:4e:9d:6c:5e:d8:27:0c:3b:d7:a4:1d:
2f:0d:a0:99:8f:b5:71:93:21:b4:87:be:b4:1c:77:
a0:b9:cd:91:bd:9c:d0:b9:81:50:12:63:d2:0a:a9:
61:05:91:19:27:f7:ea:9d:8e:48:65:2e:1a:e7:fd:
f1:b7
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Subject Alternative Name:
DNS:web-server-tokens-off.nginx-proxy.tld
Signature Algorithm: sha256WithRSAEncryption
5b:b7:74:ad:07:08:65:3c:8e:02:50:a9:b6:f4:8d:47:95:6f:
e0:ba:5a:8c:ae:5c:32:88:8b:45:04:48:ce:3d:72:45:d7:7e:
1e:d7:75:17:30:98:90:21:4c:67:e2:57:1d:c9:fa:03:f4:81:
64:cf:d2:b3:85:71:be:53:b9:2a:fd:89:04:a6:b1:88:0a:0a:
f1:5c:93:9b:fb:4f:86:0e:c5:4d:6a:ff:54:7b:07:f1:7e:d1:
8a:6b:fa:3b:f3:5c:d2:1b:2c:86:05:4c:e0:b4:04:0d:c7:db:
0b:89:b4:33:09:b6:1a:f0:cb:d4:ae:2c:05:63:a4:18:19:52:
c7:15:21:ac:ae:9e:15:b9:b0:58:0c:96:df:7b:77:46:ef:59:
a7:96:56:da:f6:f6:81:9f:10:7d:5a:48:68:0c:28:02:5d:7b:
69:4d:89:41:e2:88:6d:c6:22:45:6a:34:1b:ba:9b:6f:d6:2d:
c2:55:b1:73:b4:bb:f5:06:d6:5f:ed:01:d1:3c:51:8b:e2:6c:
31:d7:6b:a5:bd:05:e3:9a:97:15:40:bf:bb:8f:81:e5:bf:bc:
06:66:47:84:fe:f7:06:fb:5d:35:9e:04:26:0d:aa:3d:b5:92:
6b:90:c2:1c:17:ac:c1:95:d9:6b:f1:5d:0a:09:9f:a7:a6:ca:
3b:45:a4:59
-----BEGIN CERTIFICATE-----
MIIDHzCCAgegAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPzEfMB0GA1UECgwWbmdp
bngtcHJveHkgdGVzdCBzdWl0ZTEcMBoGA1UEAwwTd3d3Lm5naW54LXByb3h5LnRs
ZDAeFw0yMTA1MTExODI1NDlaFw00ODA5MjYxODI1NDlaMDAxLjAsBgNVBAMMJXdl
Yi1zZXJ2ZXItdG9rZW5zLW9mZi5uZ2lueC1wcm94eS50bGQwggEiMA0GCSqGSIb3
DQEBAQUAA4IBDwAwggEKAoIBAQC0+p2KdD8X6pkcRXEYkOuSNTjXkCGBCpEFQc+1
hzS92Ht/fQYz+JRnjuQHVH+3YsV2bH98GSUZLDaaJlSOLZcCeDHGE9Ot8zFi5s+W
rmM33b1zy077P5tlZ5fYWl0OcrERqw7XI6m3It4jdH6IfCiYqW4A9L6Maeo/M4sZ
l9obpmW1WpIBPDoTawAC4Zh409rqppwzsB2fAsTx0NbeevdCEksx++3p19gV6E4Y
kXydvw+wEtbigIt67xdwUfQ8t0PLVmGvYXpOnWxe2CcMO9ekHS8NoJmPtXGTIbSH
vrQcd6C5zZG9nNC5gVASY9IKqWEFkRkn9+qdjkhlLhrn/fG3AgMBAAGjNDAyMDAG
A1UdEQQpMCeCJXdlYi1zZXJ2ZXItdG9rZW5zLW9mZi5uZ2lueC1wcm94eS50bGQw
DQYJKoZIhvcNAQELBQADggEBAFu3dK0HCGU8jgJQqbb0jUeVb+C6WoyuXDKIi0UE
SM49ckXXfh7XdRcwmJAhTGfiVx3J+gP0gWTP0rOFcb5TuSr9iQSmsYgKCvFck5v7
T4YOxU1q/1R7B/F+0Ypr+jvzXNIbLIYFTOC0BA3H2wuJtDMJthrwy9SuLAVjpBgZ
UscVIayunhW5sFgMlt97d0bvWaeWVtr29oGfEH1aSGgMKAJde2lNiUHiiG3GIkVq
NBu6m2/WLcJVsXO0u/UG1l/tAdE8UYvibDHXa6W9BeOalxVAv7uPgeW/vAZmR4T+
9wb7XTWeBCYNqj21kmuQwhwXrMGV2WvxXQoJn6emyjtFpFk=
-----END CERTIFICATE-----

View file

@ -0,0 +1,27 @@
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAtPqdinQ/F+qZHEVxGJDrkjU415AhgQqRBUHPtYc0vdh7f30G
M/iUZ47kB1R/t2LFdmx/fBklGSw2miZUji2XAngxxhPTrfMxYubPlq5jN929c8tO
+z+bZWeX2FpdDnKxEasO1yOptyLeI3R+iHwomKluAPS+jGnqPzOLGZfaG6ZltVqS
ATw6E2sAAuGYeNPa6qacM7AdnwLE8dDW3nr3QhJLMfvt6dfYFehOGJF8nb8PsBLW
4oCLeu8XcFH0PLdDy1Zhr2F6Tp1sXtgnDDvXpB0vDaCZj7VxkyG0h760HHeguc2R
vZzQuYFQEmPSCqlhBZEZJ/fqnY5IZS4a5/3xtwIDAQABAoIBAAaBi/BSRYJimKZ/
iJVNgGp9J1H4iHvPGW+K8iCgf7Dje20V3Yc4xH0EkgYBb6X0Ew0y0VJwxPimsj/Q
aPHDic446/Em/VEfkQLxMT1Ff6OegRUMlgZKPxfiJX9NoFLIpLzx3VK2oX9H7Zxw
r6vQatUyIhY+tiruE9G51KJS5zBfN388ErfRUI8ByBaDGH0huA6kTBcNffhCfZr5
9naWSIIcuBe8v7z6nAaeYL00q1q3vuWPmuQduSgsmef7QuN71CIxuOAqXTJl8koS
LYNbj8yvIy3nOF90D+uZD/Pa2Y0kB6aum09hbUP15K0QFKulbKLRQ60IuvRcw3Qv
MM177OECgYEA5Rw3qUcoTDfsx+nu2BxECj62uyNVZfX/QMf7dvzCqjXuOhij+KBB
U9xnNfuLc4HfCXx/rMg5dGExEBbD2iHAo0nvnCSxzLJmF6i66Uves0VWISXcv2Au
L0TWMhhsbDFoqkWuxXr69oNwKyl9yFRFWEY3p3G+aBAEqWZ1lOkU8O0CgYEAyjhC
bN4mJJYhvX+cXhv+89Z+JIDAvtvQ5Vy7kxvhQUTx2By6rWKKrBPdTnzsxBGKqQwv
lXzfgj/MlIr6A6QDReGwU3ZXTJqSGEuT8Ra9SbjczQgaGOrPCrWhnbeZ18iM67pJ
LPfLgdRdkh3XgbOOKcDhpg2KybbbyXx6Q2xb7LMCgYEAzKHKWUh0BreApgIcUSvV
3ayr+zOQ5/Oy24KC6IDTwcFPmNY/RiakkqluCfo1UKKzuj5XrtRa9MaGUs9yeJbi
/zVfbQAdSi4hH4qV/x/Dtiz8w7iUlN3sAk4iXjYQSQZMbKC2fC3ej2VQP0zcypvy
H+j/dnASV9HOyBr6dFlGWfUCgYB3gfYntsXd+2fnQOJdb7glzM5xrjG62dfDpSEp
mGFwHFm8+YWNcF45weeZOhUG7sL+krgQZWMF68RwyQ1mV2ijxPRa7uY63GKYvxmo
cmLdjcXX2gDqVuKTFrJzrgzaTKiTq10RmUQI70N5Ve+FtGLA5D+2zewGt+1+TvVG
oWRWJwKBgAUpJ/NXOB82ie9RtwfAeuiD0yDPM3gNFVe0udAyG/71nXyHiW5aHn/w
H+QSliw7gqir4u6bcrprFQMcwiowtCfeDkcXoQCOBx6TvL2zZTrG7J/68yDHfHGg
w3eFN7ac8FsliRpT+UVKM97zJXcWFkai5Q+R7oKsWXRVXQUZZxg9
-----END RSA PRIVATE KEY-----

View file

@ -1,5 +1,3 @@
import pytest
def test_arbitrary_headers_are_passed_on(docker_compose, nginxproxy):
r = nginxproxy.get("http://web.nginx-proxy.tld/headers", headers={'Foo': 'Bar'})
assert r.status_code == 200
@ -79,3 +77,23 @@ def test_httpoxy_safe(docker_compose, nginxproxy):
assert r.status_code == 200
assert "Proxy:" not in r.text
def test_no_host_server_tokens_off(docker_compose, nginxproxy):
ip = nginxproxy.get_ip()
r = nginxproxy.get(f"http://{ip}/headers")
assert r.status_code == 503
assert r.headers["Server"] == "nginx"
def test_server_tokens_on(docker_compose, nginxproxy):
r = nginxproxy.get("http://web.nginx-proxy.tld/headers")
assert r.status_code == 200
assert "Host: web.nginx-proxy.tld" in r.text
assert r.headers["Server"].startswith("nginx/")
def test_server_tokens_off(docker_compose, nginxproxy):
r = nginxproxy.get("http://web-server-tokens-off.nginx-proxy.tld/headers")
assert r.status_code == 200
assert "Host: web-server-tokens-off.nginx-proxy.tld" in r.text
assert r.headers["Server"] == "nginx"

View file

@ -6,9 +6,17 @@ web:
WEB_PORTS: 80
VIRTUAL_HOST: web.nginx-proxy.tld
web-server-tokens-off:
image: web
expose:
- "80"
environment:
WEB_PORTS: 80
VIRTUAL_HOST: web-server-tokens-off.nginx-proxy.tld
SERVER_TOKENS: "off"
sut:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- ../lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro

View file

@ -80,3 +80,24 @@ def test_httpoxy_safe(docker_compose, nginxproxy):
assert r.status_code == 200
assert "Proxy:" not in r.text
@pytest.mark.filterwarnings('ignore::urllib3.exceptions.InsecureRequestWarning')
def test_no_host_server_tokens_off(docker_compose, nginxproxy):
ip = nginxproxy.get_ip()
r = nginxproxy.get(f"https://{ip}/headers", verify=False)
assert r.status_code == 503
assert r.headers["Server"] == "nginx"
def test_server_tokens_on(docker_compose, nginxproxy):
r = nginxproxy.get("https://web.nginx-proxy.tld/headers")
assert r.status_code == 200
assert "Host: web.nginx-proxy.tld" in r.text
assert r.headers["Server"].startswith("nginx/")
def test_server_tokens_off(docker_compose, nginxproxy):
r = nginxproxy.get("https://web-server-tokens-off.nginx-proxy.tld/headers")
assert r.status_code == 200
assert "Host: web-server-tokens-off.nginx-proxy.tld" in r.text
assert r.headers["Server"] == "nginx"

View file

@ -6,11 +6,23 @@ web:
WEB_PORTS: 80
VIRTUAL_HOST: web.nginx-proxy.tld
web-server-tokens-off:
image: web
expose:
- "80"
environment:
WEB_PORTS: 80
VIRTUAL_HOST: web-server-tokens-off.nginx-proxy.tld
SERVER_TOKENS: "off"
sut:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- ./certs/web.nginx-proxy.tld.crt:/etc/nginx/certs/default.crt:ro
- ./certs/web.nginx-proxy.tld.key:/etc/nginx/certs/default.key:ro
- ./certs/web.nginx-proxy.tld.crt:/etc/nginx/certs/web.nginx-proxy.tld.crt:ro
- ./certs/web.nginx-proxy.tld.key:/etc/nginx/certs/web.nginx-proxy.tld.key:ro
- ../lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro
- ./certs/web-server-tokens-off.nginx-proxy.tld.crt:/etc/nginx/certs/web-server-tokens-off.nginx-proxy.tld.crt:ro
- ./certs/web-server-tokens-off.nginx-proxy.tld.key:/etc/nginx/certs/web-server-tokens-off.nginx-proxy.tld.key:ro

8
test/test_http_port.py Normal file
View file

@ -0,0 +1,8 @@
import pytest
@pytest.mark.parametrize("subdomain", ["foo", "bar"])
def test_web1_http_custom_port(docker_compose, nginxproxy, subdomain):
r = nginxproxy.get("http://%s.nginx-proxy.tld:8080/port" % subdomain, allow_redirects=False)
assert r.status_code == 200
assert "answer from port 81\n" in r.text

14
test/test_http_port.yml Normal file
View file

@ -0,0 +1,14 @@
web1:
image: web
expose:
- "81"
environment:
WEB_PORTS: "81"
VIRTUAL_HOST: "*.nginx-proxy.tld"
sut:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
environment:
HTTP_PORT: 8080

View file

@ -1,24 +1,39 @@
web1:
image: web
expose:
- "81"
environment:
WEB_PORTS: 81
VIRTUAL_HOST: web1.nginx-proxy.tld
version: '2'
web2:
image: web
expose:
- "82"
environment:
WEB_PORTS: 82
VIRTUAL_HOST: web2.nginx-proxy.tld
networks:
net1:
enable_ipv6: true
ipam:
config:
- subnet: fd00:1::/80
services:
web1:
image: web
expose:
- "81"
environment:
WEB_PORTS: 81
VIRTUAL_HOST: web1.nginx-proxy.tld
networks:
- net1
web2:
image: web
expose:
- "82"
environment:
WEB_PORTS: 82
VIRTUAL_HOST: web2.nginx-proxy.tld
networks:
- net1
sut:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- ./lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro
environment:
ENABLE_IPV6: "true"
sut:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
environment:
ENABLE_IPV6: "true"
networks:
- net1

View file

@ -11,4 +11,3 @@ sut:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- ./lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro

View file

@ -9,7 +9,6 @@ services:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- ./lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro
networks:
- net1
- net2

View file

@ -0,0 +1,8 @@
import pytest
import re
def test_answer_is_served_from_virtual_port_which_is_ureachable(docker_compose, nginxproxy):
r = nginxproxy.get("http://web.nginx-proxy.tld/port")
assert r.status_code == 502
assert re.search(r"\n\s+server \d+\.\d+\.\d+\.\d+:90;\n", nginxproxy.get_conf().decode('ASCII'))

View file

@ -0,0 +1,14 @@
web:
image: web
expose:
- "81"
environment:
WEB_PORTS: "81"
VIRTUAL_HOST: "web.nginx-proxy.tld"
VIRTUAL_PORT: "90"
sut:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro

View file

@ -12,4 +12,3 @@ sut:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- ../lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro

View file

@ -11,4 +11,3 @@ sut:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- ../lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro

View file

@ -11,4 +11,3 @@ sut:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- ../lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro

View file

@ -22,3 +22,8 @@ def test_forwards_to_web2(docker_compose, nginxproxy):
def test_ipv6_is_disabled_by_default(docker_compose, nginxproxy):
with pytest.raises(ConnectionError):
nginxproxy.get("http://nginx-proxy/port", ipv6=True)
def test_container_version_is_displayed(docker_compose, nginxproxy):
conf = nginxproxy.get_conf().decode('ASCII')
assert "# nginx-proxy version : test" in conf

View file

@ -1,22 +1,37 @@
web1:
image: web
expose:
- "81"
environment:
WEB_PORTS: 81
VIRTUAL_HOST: web1.nginx-proxy.tld
version: '2'
web2:
image: web
expose:
- "82"
environment:
WEB_PORTS: 82
VIRTUAL_HOST: web2.nginx-proxy.tld
networks:
net1:
enable_ipv6: true
ipam:
config:
- subnet: fd00:1::/80
services:
web1:
image: web
expose:
- "81"
environment:
WEB_PORTS: 81
VIRTUAL_HOST: web1.nginx-proxy.tld
networks:
- net1
web2:
image: web
expose:
- "82"
environment:
WEB_PORTS: 82
VIRTUAL_HOST: web2.nginx-proxy.tld
networks:
- net1
sut:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- ./lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro
sut:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
networks:
- net1

15
test/test_raw-ip-vhost.py Normal file
View file

@ -0,0 +1,15 @@
import pytest
def test_raw_ipv4_vhost_forwards_to_web1(docker_compose, nginxproxy):
r = nginxproxy.get("http://172.20.0.4")
assert r.status_code == 200
web1_container = docker_compose.containers.get("web1")
assert r.text == f"I'm {web1_container.id[:12]}\n"
def test_raw_ipv6_vhost_forwards_to_web2(docker_compose, nginxproxy):
r = nginxproxy.get("http://[fd00::4]", ipv6=True)
assert r.status_code == 200
web2_container = docker_compose.containers.get("web2")
assert r.text == f"I'm {web2_container.id[:12]}\n"

View file

@ -0,0 +1,47 @@
version: '2'
networks:
net1:
enable_ipv6: true
ipam:
config:
- subnet: 172.20.0.0/16
- subnet: fd00::/80
services:
web1:
container_name: web1
image: web
expose:
- "81"
environment:
WEB_PORTS: 81
VIRTUAL_HOST: "172.20.0.4"
networks:
net1:
ipv4_address: 172.20.0.2
ipv6_address: fd00::2
web2:
container_name: web2
image: web
expose:
- "82"
environment:
WEB_PORTS: 82
VIRTUAL_HOST: "[fd00::4]"
networks:
net1:
ipv4_address: 172.20.0.3
ipv6_address: fd00::3
sut:
image: nginxproxy/nginx-proxy:test
environment:
ENABLE_IPV6: "true"
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
networks:
net1:
ipv4_address: 172.20.0.4
ipv6_address: fd00::4

View file

@ -0,0 +1,8 @@
import pytest
def test_web_has_no_server_down(docker_compose, nginxproxy):
conf = nginxproxy.get_conf().decode('ASCII')
r = nginxproxy.get("http://web.nginx-proxy.tld/port")
assert r.status_code == 200
assert (r.text == "answer from port 81\n") or (r.text == "answer from port 82\n")
assert conf.count("server 127.0.0.1 down;") == 0

View file

@ -0,0 +1,29 @@
web1:
image: web
expose:
- "81"
environment:
WEB_PORTS: 81
VIRTUAL_HOST: web.nginx-proxy.tld
web2:
image: web
expose:
- "82"
environment:
WEB_PORTS: 83
VIRTUAL_HOST: web.nginx-proxy.tld
web3:
image: web
expose:
- "83"
environment:
WEB_PORTS: 83
VIRTUAL_HOST: web.nginx-proxy.tld
net: "none"
sut:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro

View file

@ -0,0 +1,8 @@
import pytest
def test_web_has_no_server_down(docker_compose, nginxproxy):
conf = nginxproxy.get_conf().decode('ASCII')
r = nginxproxy.get("http://web.nginx-proxy.tld/port")
assert r.status_code == 200
assert r.text == "answer from port 81\n"
assert conf.count("server 127.0.0.1 down;") == 0

View file

@ -1,8 +1,12 @@
web:
image: web
expose:
- "81"
environment:
WEB_PORTS: 81
VIRTUAL_HOST: web.nginx-proxy.tld
sut:
image: nginxproxy/nginx-proxy:test
container_name: nginxproxy
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- ./certs:/etc/nginx/certs:ro
environment:
- DHPARAM_BITS=256

View file

@ -0,0 +1,7 @@
import pytest
def test_web_has_server_down(docker_compose, nginxproxy):
conf = nginxproxy.get_conf().decode('ASCII')
r = nginxproxy.get("http://web.nginx-proxy.tld/port")
assert r.status_code in [502, 503]
assert conf.count("server 127.0.0.1 down;") == 1

View file

@ -0,0 +1,13 @@
web:
image: web
expose:
- "81"
environment:
WEB_PORTS: 81
VIRTUAL_HOST: web.nginx-proxy.tld
net: "none"
sut:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro

View file

@ -0,0 +1,8 @@
-----BEGIN DH PARAMETERS-----
MIIBCAKCAQEA//////////+t+FRYortKmq/cViAnPTzx2LnFg84tNpWp4TZBFGQz
+8yTnc4kmz75fS/jY2MMddj2gbICrsRhetPfHtXV/WVhJDP1H18GbtCFY2VVPe0a
87VXE15/V8k1mE8McODmi3fipona8+/och3xWKE2rec1MKzKT0g6eXq8CrGCsyT7
YdEIqUuyyOP7uWrat2DX9GgdT0Kj3jlN9K5W7edjcrsZCwenyO4KbXCeAvzhzffi
7MA0BM0oNC9hkXL+nOmFg/+OTxIy7vKBg8P+OxtMb61zO7X8vC7CIAXFjvGDfRaD
ssbzSibBsu/6iGtCOGEoXJf//////////wIBAg==
-----END DH PARAMETERS-----

View file

@ -1,5 +1,6 @@
import re
import subprocess
import os
import backoff
import docker
@ -15,7 +16,7 @@ docker_client = docker.from_env()
###############################################################################
@backoff.on_exception(backoff.constant, AssertionError, interval=2, max_tries=15, jitter=None)
def assert_log_contains(expected_log_line):
def assert_log_contains(expected_log_line, container_name="nginxproxy"):
"""
Check that the nginx-proxy container log contains a given string.
The backoff decorator will retry the check 15 times with a 2 seconds delay.
@ -24,9 +25,9 @@ def assert_log_contains(expected_log_line):
:return: None
:raises: AssertError if the expected string is not found in the log
"""
sut_container = docker_client.containers.get("nginxproxy")
sut_container = docker_client.containers.get(container_name)
docker_logs = sut_container.logs(stdout=True, stderr=True, stream=False, follow=False)
assert expected_log_line in docker_logs
assert bytes(expected_log_line, encoding="utf8") in docker_logs
def require_openssl(required_version):
@ -42,7 +43,7 @@ def require_openssl(required_version):
"""
def versiontuple(v):
clean_v = re.sub("[^\d\.]", "", v)
clean_v = re.sub(r"[^\d\.]", "", v)
return tuple(map(int, (clean_v.split("."))))
try:
@ -52,10 +53,92 @@ def require_openssl(required_version):
else:
if not command_output:
raise Exception("Could not get openssl version")
openssl_version = command_output.split()[1]
openssl_version = str(command_output.split()[1])
return pytest.mark.skipif(
versiontuple(openssl_version) < versiontuple(required_version),
reason="openssl v%s is less than required version %s" % (openssl_version, required_version))
reason=f"openssl v{openssl_version} is less than required version {required_version}")
@require_openssl("1.0.2")
def negotiate_cipher(sut_container, additional_params='', grep='Cipher is'):
host = f"{sut_container.attrs['NetworkSettings']['IPAddress']}:443"
try:
# Enforce TLS 1.2 as newer versions don't support custom dhparam or ciphersuite preference.
# The empty `echo` is to provide `openssl` user input, so that the process exits: https://stackoverflow.com/a/28567565
# `shell=True` enables using a single string to execute as a shell command.
# `text=True` prevents the need to compare against byte strings.
# `stderr=subprocess.PIPE` removes the output to stderr being interleaved with test case status (output during exceptions).
return subprocess.check_output(
f"echo '' | openssl s_client -connect {host} -tls1_2 {additional_params} | grep '{grep}'",
shell=True,
text=True,
stderr=subprocess.PIPE,
)
except subprocess.CalledProcessError as e:
# Output a more helpful error, the original exception in this case isn't that helpful.
# `from None` to ignore undesired output from exception chaining.
raise Exception("Failed to process CLI request:\n" + e.stderr) from None
# The default `dh_bits` can vary due to configuration.
# `additional_params` allows for adjusting the request to a specific `VIRTUAL_HOST`,
# where DH size can differ from the configured global default DH size.
def can_negotiate_dhe_ciphersuite(sut_container, dh_bits=4096, additional_params=''):
openssl_params = f"-cipher 'EDH' {additional_params}"
r = negotiate_cipher(sut_container, openssl_params)
assert "New, TLSv1.2, Cipher is DHE-RSA-AES256-GCM-SHA384\n" == r
r2 = negotiate_cipher(sut_container, openssl_params, "Server Temp Key")
assert f"Server Temp Key: DH, {dh_bits} bits" in r2
def cannot_negotiate_dhe_ciphersuite(sut_container):
# Fail to negotiate a DHE cipher suite:
r = negotiate_cipher(sut_container, "-cipher 'EDH'")
assert "New, (NONE), Cipher is (NONE)\n" == r
# Correctly establish a connection (TLS 1.2):
r2 = negotiate_cipher(sut_container)
assert "New, TLSv1.2, Cipher is ECDHE-RSA-AES256-GCM-SHA384\n" == r2
r3 = negotiate_cipher(sut_container, grep="Server Temp Key")
assert "X25519" in r3
# To verify self-signed certificates, the file path to their CA cert must be provided.
# Use the `fqdn` arg to specify the `VIRTUAL_HOST` to request for verification for that cert.
#
# Resolves the following stderr warnings regarding self-signed cert verification and missing SNI:
# `Can't use SSL_get_servername`
# `verify error:num=20:unable to get local issuer certificate`
# `verify error:num=21:unable to verify the first certificate`
#
# The stderr output is hidden due to running the openssl command with `stderr=subprocess.PIPE`.
def can_verify_chain_of_trust(sut_container, ca_cert, fqdn):
openssl_params = f"-CAfile '{ca_cert}' -servername '{fqdn}'"
r = negotiate_cipher(sut_container, openssl_params, "Verify return code")
assert "Verify return code: 0 (ok)" in r
def should_be_equivalent_content(sut_container, expected, actual):
expected_checksum = sut_container.exec_run(f"md5sum {expected}").output.split()[0]
actual_checksum = sut_container.exec_run(f"md5sum {actual}").output.split()[0]
assert expected_checksum == actual_checksum
# Parse array of container ENV, splitting at the `=` and returning the value, otherwise `None`
def get_env(sut_container, var):
env = sut_container.attrs['Config']['Env']
for e in env:
if e.startswith(var):
return e.split('=')[1]
return None
###############################################################################
@ -64,30 +147,131 @@ def require_openssl(required_version):
#
###############################################################################
def test_dhparam_is_not_generated_if_present(docker_compose):
sut_container = docker_client.containers.get("nginxproxy")
def test_default_dhparam_is_ffdhe4096(docker_compose):
container_name="dh-default"
sut_container = docker_client.containers.get(container_name)
assert sut_container.status == "running"
assert_log_contains("Custom dhparam.pem file found, generation skipped")
assert_log_contains("Setting up DH Parameters..", container_name)
# Make sure the dhparam in use is not the default, pre-generated one
default_checksum = sut_container.exec_run("md5sum /app/dhparam.pem.default").split()
current_checksum = sut_container.exec_run("md5sum /etc/nginx/dhparam/dhparam.pem").split()
assert default_checksum[0] != current_checksum[0]
# `dhparam.pem` contents should match the default (ffdhe4096.pem):
should_be_equivalent_content(
sut_container,
"/app/dhparam/ffdhe4096.pem",
"/etc/nginx/dhparam/dhparam.pem"
)
can_negotiate_dhe_ciphersuite(sut_container, 4096)
# Overrides default DH group via ENV `DHPARAM_BITS=3072`:
def test_can_change_dhparam_group(docker_compose):
container_name="dh-env"
sut_container = docker_client.containers.get(container_name)
assert sut_container.status == "running"
assert_log_contains("Setting up DH Parameters..", container_name)
# `dhparam.pem` contents should not match the default (ffdhe4096.pem):
should_be_equivalent_content(
sut_container,
"/app/dhparam/ffdhe3072.pem",
"/etc/nginx/dhparam/dhparam.pem"
)
can_negotiate_dhe_ciphersuite(sut_container, 3072)
def test_fail_if_dhparam_group_not_supported(docker_compose):
container_name="invalid-group-1024"
sut_container = docker_client.containers.get(container_name)
assert sut_container.status == "exited"
DHPARAM_BITS = get_env(sut_container, "DHPARAM_BITS")
assert DHPARAM_BITS == "1024"
assert_log_contains(
f"ERROR: Unsupported DHPARAM_BITS size: {DHPARAM_BITS}. Use: 2048, 3072, or 4096 (default).",
container_name
)
# Overrides default DH group by providing a custom `/etc/nginx/dhparam/dhparam.pem`:
def test_custom_dhparam_is_supported(docker_compose):
container_name="dh-file"
sut_container = docker_client.containers.get(container_name)
assert sut_container.status == "running"
assert_log_contains(
"Warning: A custom dhparam.pem file was provided. Best practice is to use standardized RFC7919 DHE groups instead.",
container_name
)
# `dhparam.pem` contents should not match the default (ffdhe4096.pem):
should_be_equivalent_content(
sut_container,
"/app/dhparam/ffdhe3072.pem",
"/etc/nginx/dhparam/dhparam.pem"
)
can_negotiate_dhe_ciphersuite(sut_container, 3072)
# Only `web2` has a site-specific DH param file (which overrides all other DH config)
# Other tests here use `web5` explicitly, or implicitly (via ENV `DEFAULT_HOST`, otherwise first HTTPS server)
def test_custom_dhparam_is_supported_per_site(docker_compose):
container_name="dh-file"
sut_container = docker_client.containers.get(container_name)
assert sut_container.status == "running"
# A site specific `dhparam.pem` with DH group size of 2048-bit.
# DH group size should not match the:
# - 4096-bit default.
# - 3072-bit default, overriden by file.
should_be_equivalent_content(
sut_container,
"/app/dhparam/ffdhe2048.pem",
"/etc/nginx/certs/web2.nginx-proxy.tld.dhparam.pem"
)
# `-servername` required for nginx-proxy to respond with site-specific DH params used:
can_negotiate_dhe_ciphersuite(sut_container, 2048, '-servername web2.nginx-proxy.tld')
# --Unrelated to DH support--
# - `web5` is missing a certificate, but falls back to available `/etc/nginx/certs/nginx-proxy.tld.crt` via `nginx.tmpl` "closest" result.
# - `web2` has it's own cert provisioned at `/etc/nginx/certs/web2.nginx-proxy.tld.crt`.
can_verify_chain_of_trust(
sut_container,
ca_cert = f"{os.getcwd()}/certs/ca-root.crt",
fqdn = 'web2.nginx-proxy.tld'
)
# NOTE: These two tests will fail without the ENV `DEFAULT_HOST` to prevent
# accidentally falling back to `web2` as the default server, which has explicit DH params configured.
# Only copying DH params is skipped, not explicit usage via user providing custom files.
def test_can_skip_dhparam(docker_compose):
container_name="dh-skip"
sut_container = docker_client.containers.get(container_name)
assert sut_container.status == "running"
assert_log_contains("Skipping Diffie-Hellman parameters setup.", container_name)
cannot_negotiate_dhe_ciphersuite(sut_container)
def test_can_skip_dhparam_backward_compatibility(docker_compose):
container_name="dh-skip-backward"
sut_container = docker_client.containers.get(container_name)
assert sut_container.status == "running"
assert_log_contains("Warning: The DHPARAM_GENERATION environment variable is deprecated, please consider using DHPARAM_SKIP set to true instead.", container_name)
assert_log_contains("Skipping Diffie-Hellman parameters setup.", container_name)
cannot_negotiate_dhe_ciphersuite(sut_container)
def test_web5_https_works(docker_compose, nginxproxy):
r = nginxproxy.get("https://web5.nginx-proxy.tld/port", allow_redirects=False)
assert r.status_code == 200
assert "answer from port 85\n" in r.text
@require_openssl("1.0.2")
def test_web5_dhparam_is_used(docker_compose):
sut_container = docker_client.containers.get("nginxproxy")
assert sut_container.status == "running"
host = "%s:443" % sut_container.attrs["NetworkSettings"]["IPAddress"]
r = subprocess.check_output(
"echo '' | openssl s_client -connect %s -cipher 'EDH' | grep 'Server Temp Key'" % host, shell=True)
assert "Server Temp Key: X25519, 253 bits\n" == r

View file

@ -6,11 +6,68 @@ web5:
WEB_PORTS: "85"
VIRTUAL_HOST: "web5.nginx-proxy.tld"
# Intended for testing with `dh-file` container.
# VIRTUAL_HOST is paired with site-specific DH param file.
# DEFAULT_HOST is required to avoid defaulting to web2,
# if not specifying FQDN (`-servername`) in openssl queries.
web2:
image: web
expose:
- "85"
environment:
WEB_PORTS: "85"
VIRTUAL_HOST: "web2.nginx-proxy.tld"
sut:
image: nginxproxy/nginx-proxy:test
container_name: nginxproxy
# sut - System Under Test
# `docker.sock` required for functionality
# `certs` required to enable HTTPS via template
with_default_group:
container_name: dh-default
image: &img-nginxproxy nginxproxy/nginx-proxy:test
environment: &env-common
- &default-host DEFAULT_HOST=web5.nginx-proxy.tld
volumes: &vols-common
- &docker-sock /var/run/docker.sock:/tmp/docker.sock:ro
- &nginx-certs ./certs:/etc/nginx/certs:ro
with_alternative_group:
container_name: dh-env
environment:
- DHPARAM_BITS=3072
- *default-host
image: *img-nginxproxy
volumes: *vols-common
with_invalid_group:
container_name: invalid-group-1024
environment:
- DHPARAM_BITS=1024
- *default-host
image: *img-nginxproxy
volumes: *vols-common
with_custom_file:
container_name: dh-file
image: *img-nginxproxy
environment: *env-common
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- ../lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro
- ./certs:/etc/nginx/certs:ro
- *docker-sock
- *nginx-certs
- ../../dhparam/ffdhe3072.pem:/etc/nginx/dhparam/dhparam.pem:ro
with_skip:
container_name: dh-skip
environment:
- DHPARAM_SKIP=true
- *default-host
image: *img-nginxproxy
volumes: *vols-common
with_skip_backward:
container_name: dh-skip-backward
environment:
- DHPARAM_GENERATION=false
- *default-host
image: *img-nginxproxy
volumes: *vols-common

View file

@ -38,5 +38,4 @@ sut:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- ../lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro
- ./certs:/etc/nginx/certs:ro

View file

@ -0,0 +1,14 @@
import pytest
@pytest.mark.parametrize("subdomain", ["foo", "bar"])
def test_web1_http_redirects_to_https(docker_compose, nginxproxy, subdomain):
r = nginxproxy.get("http://%s.nginx-proxy.tld:8080/" % subdomain, allow_redirects=False)
assert r.status_code == 301
assert "Location" in r.headers
assert "https://%s.nginx-proxy.tld:8443/" % subdomain == r.headers['Location']
@pytest.mark.parametrize("subdomain", ["foo", "bar"])
def test_web1_https_is_forwarded(docker_compose, nginxproxy, subdomain):
r = nginxproxy.get("https://%s.nginx-proxy.tld:8443/port" % subdomain, allow_redirects=False)
assert r.status_code == 200
assert "answer from port 81\n" in r.text

View file

@ -0,0 +1,16 @@
web1:
image: web
expose:
- "81"
environment:
WEB_PORTS: "81"
VIRTUAL_HOST: "*.nginx-proxy.tld"
sut:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- ./certs:/etc/nginx/certs:ro
environment:
HTTP_PORT: 8080
HTTPS_PORT: 8443

View file

@ -12,5 +12,4 @@ sut:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- ../lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro
- ./certs:/etc/nginx/certs:ro

View file

@ -12,4 +12,3 @@ sut:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- ../lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro

View file

@ -12,5 +12,4 @@ sut:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- ../lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro
- ./certs:/etc/nginx/certs:ro

View file

@ -3,21 +3,21 @@ import pytest
@pytest.mark.parametrize("subdomain", ["foo", "bar"])
def test_web1_http_redirects_to_https(docker_compose, nginxproxy, subdomain):
r = nginxproxy.get("http://%s.nginx-proxy.tld/" % subdomain, allow_redirects=False)
r = nginxproxy.get(f"http://{subdomain}.nginx-proxy.tld/", allow_redirects=False)
assert r.status_code == 301
assert "Location" in r.headers
assert "https://%s.nginx-proxy.tld/" % subdomain == r.headers['Location']
assert f"https://{subdomain}.nginx-proxy.tld/" == r.headers['Location']
@pytest.mark.parametrize("subdomain", ["foo", "bar"])
def test_web1_https_is_forwarded(docker_compose, nginxproxy, subdomain):
r = nginxproxy.get("https://%s.nginx-proxy.tld/port" % subdomain, allow_redirects=False)
r = nginxproxy.get(f"https://{subdomain}.nginx-proxy.tld/port", allow_redirects=False)
assert r.status_code == 200
assert "answer from port 81\n" in r.text
@pytest.mark.parametrize("subdomain", ["foo", "bar"])
def test_web1_HSTS_policy_is_active(docker_compose, nginxproxy, subdomain):
r = nginxproxy.get("https://%s.nginx-proxy.tld/port" % subdomain, allow_redirects=False)
r = nginxproxy.get(f"https://{subdomain}.nginx-proxy.tld/port", allow_redirects=False)
assert "answer from port 81\n" in r.text
assert "Strict-Transport-Security" in r.headers

View file

@ -10,5 +10,4 @@ sut:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- ../lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro
- ./certs:/etc/nginx/certs:ro

View file

@ -7,7 +7,6 @@ services:
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- ./certs:/etc/nginx/certs:ro
- ../../lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro
web1:
image: web

View file

@ -1,5 +1,5 @@
import pytest
from backports.ssl_match_hostname import CertificateError
from ssl import CertificateError
from requests.exceptions import SSLError
@ -9,21 +9,21 @@ from requests.exceptions import SSLError
(3, False),
])
def test_http_redirects_to_https(docker_compose, nginxproxy, subdomain, should_redirect_to_https):
r = nginxproxy.get("http://%s.web.nginx-proxy.tld/port" % subdomain)
r = nginxproxy.get(f"http://{subdomain}.web.nginx-proxy.tld/port")
if should_redirect_to_https:
assert len(r.history) > 0
assert r.history[0].is_redirect
assert r.history[0].headers.get("Location") == "https://%s.web.nginx-proxy.tld/port" % subdomain
assert "answer from port 8%s\n" % subdomain == r.text
assert r.history[0].headers.get("Location") == f"https://{subdomain}.web.nginx-proxy.tld/port"
assert f"answer from port 8{subdomain}\n" == r.text
@pytest.mark.parametrize("subdomain", [1, 2])
def test_https_get_served(docker_compose, nginxproxy, subdomain):
r = nginxproxy.get("https://%s.web.nginx-proxy.tld/port" % subdomain, allow_redirects=False)
r = nginxproxy.get(f"https://{subdomain}.web.nginx-proxy.tld/port", allow_redirects=False)
assert r.status_code == 200
assert "answer from port 8%s\n" % subdomain == r.text
assert f"answer from port 8{subdomain}\n" == r.text
@pytest.mark.filterwarnings('ignore::urllib3.exceptions.InsecureRequestWarning')
def test_web3_https_is_500_and_SSL_validation_fails(docker_compose, nginxproxy):
with pytest.raises( (CertificateError, SSLError) ) as excinfo:
nginxproxy.get("https://3.web.nginx-proxy.tld/port")

View file

@ -0,0 +1,7 @@
import pytest
import re
def test_predictable_upstream_is_present_in_nginx_generated_conf(docker_compose, nginxproxy):
conf = nginxproxy.get_conf().decode('ASCII')
assert re.search(r"upstream web\.nginx-proxy\.tld \{", conf)

View file

@ -0,0 +1,15 @@
version: '2'
services:
web:
image: web
expose:
- "80"
environment:
WEB_PORTS: 80
VIRTUAL_HOST: web.nginx-proxy.tld
sut:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro

View file

@ -0,0 +1,12 @@
import pytest
import re
def test_sha1_upstream_is_present_in_nginx_generated_conf(docker_compose, nginxproxy):
conf = nginxproxy.get_conf().decode('ASCII')
assert re.search(r"upstream 3e837201a6255962094cd6d8f61e22b07d3cc8ed \{", conf)
def test_sha1_upstream_forwards_correctly(docker_compose, nginxproxy):
r = nginxproxy.get("http://web.nginx-proxy.tld/port")
assert r.status_code == 200
assert r.text == "answer from port 80\n"

View file

@ -0,0 +1,17 @@
version: '2'
services:
web:
image: web
expose:
- "80"
environment:
WEB_PORTS: 80
VIRTUAL_HOST: web.nginx-proxy.tld
sut:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
environment:
SHA1_UPSTREAM_NAME: "true"

View file

@ -18,9 +18,9 @@ import pytest
("web4.whatever.nginx-proxy.regexp", 84),
])
def test_wildcard_prefix(docker_compose, nginxproxy, host, expected_port):
r = nginxproxy.get("http://%s/port" % host)
r = nginxproxy.get(f"http://{host}/port")
assert r.status_code == 200
assert r.text == "answer from port %s\n" % expected_port
assert r.text == f"answer from port {expected_port}\n"
@pytest.mark.parametrize("host", [
@ -28,5 +28,5 @@ def test_wildcard_prefix(docker_compose, nginxproxy, host, expected_port):
"web4.whatever.nginx-proxy.regexp-to-infinity-and-beyond"
])
def test_non_matching_host_is_503(docker_compose, nginxproxy, host):
r = nginxproxy.get("http://%s/port" % host)
r = nginxproxy.get(f"http://{host}/port")
assert r.status_code == 503, r.text

View file

@ -35,4 +35,3 @@ sut:
image: nginxproxy/nginx-proxy:test
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- ./lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro