diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index cfaa367..9824d63 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -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 diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..9056ae1 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,19 @@ +version: 2 +updates: + + # Maintain dependencies for Docker + - package-ecosystem: "docker" + directory: "/" + schedule: + interval: "daily" + labels: + - "type/build" + - "scope/dockerfile" + + # Maintain Python dependencies (test suite) + - package-ecosystem: "pip" + directory: "/test/requirements" + schedule: + interval: "daily" + labels: + - "type/ci" diff --git a/.github/workflows/docker_push.yml b/.github/workflows/docker_push.yml index 42e7ba3..0bbff10 100644 --- a/.github/workflows/docker_push.yml +++ b/.github/workflows/docker_push.yml @@ -14,10 +14,23 @@ jobs: steps: - name: Check out the repo uses: actions/checkout@v2 - - name: Push to Docker Hub - uses: docker/build-push-action@v1 + + - 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.DOCKER_USERNAME }} password: ${{ secrets.DOCKER_PASSWORD }} + + - name: Push debian image to Docker Hub + uses: docker/build-push-action@v2 + with: + file: Dockerfile + platforms: linux/amd64,linux/arm64,linux/arm/v7 repository: seitenwerke/nginx-proxy tag_with_ref: true \ No newline at end of file diff --git a/.github/workflows/dockerhub.yml b/.github/workflows/dockerhub.yml new file mode 100644 index 0000000..cb3635e --- /dev/null +++ b/.github/workflows/dockerhub.yml @@ -0,0 +1,130 @@ +name: DockerHub + +on: + workflow_dispatch: + schedule: + - cron: '0 0 * * 1' + push: + branches: + - main + tags: + - '*.*.*' + paths-ignore: + - 'test/*' + - '.gitignore' + - '.travis.yml' + - 'docker-compose-separate-containers.yml' + - 'docker-compose.yml' + - 'LICENSE' + - 'Makefile' + - '*.md' + +jobs: + multiarch-build-debian: + 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 Debian based image + id: docker_meta_debian + uses: docker/metadata-action@v3 + with: + images: | + nginxproxy/nginx-proxy + jwilder/nginx-proxy + tags: | + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} + type=raw,value=latest,enable=${{ endsWith(github.ref, github.event.repository.default_branch) }} + labels: | + org.opencontainers.image.authors=Nicolas Duchon (@buchdag), Jason Wilder + org.opencontainers.image.version=${{ env.GIT_DESCRIBE }} + + - 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 Debian based image + 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 (@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_alpine.outputs.digest }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index c79678d..541c08c 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,21 +1,46 @@ -name: Test +name: Tests on: - pull_request: + workflow_dispatch: push: - branches: - - master - - stable* - + paths-ignore: + - 'LICENSE' + - '**.md' + pull_request: + paths-ignore: + - 'LICENSE' + - '**.md' + jobs: - run-test-debian: + unit: + name: Unit Tests runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + base_docker_image: [alpine, debian] + steps: - - name: Checkout - uses: actions/checkout@v2 - - name: Setup Docker - uses: docker-practice/actions-setup-docker@master - - name: Print docker version - run: docker version - - name: Run Makefile - run: make test-debian + - uses: actions/checkout@v2 + + - name: Set up Python 3.9 + uses: actions/setup-python@v2 + with: + python-version: 3.9 + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install -r python-requirements.txt + working-directory: test/requirements + + - name: Build Docker web server image + run: make build-webserver + + - name: Build Docker nginx proxy test image + run: make build-nginx-proxy-test-${{ matrix.base_docker_image }} + + - name: Run tests + run: pytest + working-directory: test \ No newline at end of file diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 7a1c66f..0000000 --- a/.travis.yml +++ /dev/null @@ -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 diff --git a/Dockerfile b/Dockerfile index c528481..d5c71bc 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,37 +1,74 @@ -FROM nginx:1.19.3 -LABEL maintainer="Jason Wilder mail@jasonwilder.com" +# setup build arguments for version of dependencies to use +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.16.7 as gobuilder + +# Build docker-gen from scratch +FROM gobuilder as dockergen + +ARG DOCKER_GEN_VERSION + +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 +FROM gobuilder as forego + +ARG FOREGO_VERSION + +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.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 -ADD https://github.com/jwilder/forego/releases/download/v0.16.1/forego /usr/local/bin/forego -RUN chmod u+x /usr/local/bin/forego - -ENV DOCKER_GEN_VERSION 0.7.4 - -RUN wget https://github.com/jwilder/docker-gen/releases/download/$DOCKER_GEN_VERSION/docker-gen-linux-amd64-$DOCKER_GEN_VERSION.tar.gz \ - && tar -C /usr/local/bin -xvzf docker-gen-linux-amd64-$DOCKER_GEN_VERSION.tar.gz \ - && rm /docker-gen-linux-amd64-$DOCKER_GEN_VERSION.tar.gz +# 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"] diff --git a/Dockerfile.alpine b/Dockerfile.alpine index 4b5545b..2552615 100644 --- a/Dockerfile.alpine +++ b/Dockerfile.alpine @@ -1,34 +1,71 @@ -FROM nginx:1.19.3-alpine -LABEL maintainer="Jason Wilder mail@jasonwilder.com" +# setup build arguments for version of dependencies to use +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.16.7-alpine as gobuilder +RUN apk add --no-cache git musl-dev + +# Build docker-gen from scratch +FROM gobuilder as dockergen + +ARG DOCKER_GEN_VERSION + +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 +FROM gobuilder as forego + +ARG FOREGO_VERSION + +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.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 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 - + 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_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 -ADD https://github.com/jwilder/forego/releases/download/v0.16.1/forego /usr/local/bin/forego -RUN chmod u+x /usr/local/bin/forego - -ENV DOCKER_GEN_VERSION 0.7.4 - -RUN wget --quiet https://github.com/jwilder/docker-gen/releases/download/$DOCKER_GEN_VERSION/docker-gen-alpine-linux-amd64-$DOCKER_GEN_VERSION.tar.gz \ - && tar -C /usr/local/bin -xvzf docker-gen-alpine-linux-amd64-$DOCKER_GEN_VERSION.tar.gz \ - && rm /docker-gen-alpine-linux-amd64-$DOCKER_GEN_VERSION.tar.gz +# 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"] diff --git a/LICENSE b/LICENSE index fc926a8..ce7d86c 100644 --- a/LICENSE +++ b/LICENSE @@ -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 diff --git a/Makefile b/Makefile index 5f965f7..ab44880 100644 --- a/Makefile +++ b/Makefile @@ -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 jwilder/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 jwilder/nginx-proxy:test . +test-alpine: build-webserver build-nginx-proxy-test-alpine test/pytest.sh test: test-debian test-alpine diff --git a/README.md b/README.md index 5232058..bc2b1e5 100644 --- a/README.md +++ b/README.md @@ -1,44 +1,60 @@ # Seitenwerke nginx-proxy fork [![Docker Image Version (latest semver)](https://img.shields.io/docker/v/seitenwerke/nginx-proxy?label=docker%20version&sort=semver)](https://hub.docker.com/repository/docker/seitenwerke/nginx-proxy) ![Publish Docker image](https://github.com/seitenwerke/seitenwerke-nginx-proxy/workflows/Publish%20Docker%20image/badge.svg?branch=master) ![Test](https://github.com/seitenwerke/seitenwerke-nginx-proxy/workflows/Test/badge.svg) +## Push a new version +To push a new version to docker hub just create a new tag like `v1.0.1`. Github actions will then create a new container image and push +it to the docker hub automatically. See `.github/workflows/docker_push.yml` for details. + # Original Readme -![latest 0.7.0](https://img.shields.io/badge/latest-0.7.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/jwilder/nginx-proxy 'DockerHub') [![](https://img.shields.io/docker/pulls/jwilder/nginx-proxy.svg)](https://hub.docker.com/r/jwilder/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 jwilder/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 The nginx-proxy images are available in two flavors. -#### jwilder/nginx-proxy:latest +#### nginxproxy/nginx-proxy:latest -This image uses the debian:jessie based nginx image. +This image uses the debian:buster based nginx image. - $ docker pull jwilder/nginx-proxy:latest +```console +docker pull nginxproxy/nginx-proxy:latest +``` -#### jwilder/nginx-proxy:alpine +#### 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 jwilder/nginx-proxy:alpine +```console +docker pull nginxproxy/nginx-proxy:alpine +``` ### Docker Compose @@ -47,7 +63,7 @@ version: '2' services: nginx-proxy: - image: jwilder/nginx-proxy + image: nginxproxy/nginx-proxy ports: - "80:80" volumes: @@ -55,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 ``` @@ -69,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 jwilder/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 @@ -93,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 \ - --name my-nginx-proxy --net my-network jwilder/nginx-proxy -$ docker network connect my-other-network my-nginx-proxy +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 ``` 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; @@ -115,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/`. @@ -127,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 @@ -146,174 +187,138 @@ 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 jwilder/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/jwilder/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/JrCs/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 jwilder/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 2048 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 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=` -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=` 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/.chain.pem`, where `` 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/.chain.pem`, where `` 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 2048 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 \ - jwilder/nginx-proxy + nginxproxy/nginx-proxy ``` You'll need apache2-utils on the machine where you plan to create the htpasswd file. Follow these [instructions](http://httpd.apache.org/docs/2.2/programs/htpasswd.html) @@ -324,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 @@ -355,7 +359,7 @@ To add settings on a proxy-wide basis, add your configuration file under `/etc/n This can be done in a derived image by creating the file in a `RUN` command or by `COPY`ing the file into `conf.d`: ```Dockerfile -FROM jwilder/nginx-proxy +FROM nginxproxy/nginx-proxy RUN { \ echo 'server_tokens off;'; \ echo 'client_max_body_size 100m;'; \ @@ -364,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 jwilder/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 @@ -374,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 jwilder/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 jwilder/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 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: [{ tcp } { tcp } ...] + # Default virtual port: + # VIRTUAL_PORT: + # foo + server 172.18.0.9:; + # 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 @@ -413,26 +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 `jwilder/nginx-proxy:test`: +To run tests, you just need to run the command below: - docker build -t jwilder/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 jwilder/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. - -### Need help? - -If you have questions on how to use the image, please ask them on the [Q&A Group](https://groups.google.com/forum/#!forum/nginx-proxy) diff --git a/dhparam.pem.default b/dhparam.pem.default deleted file mode 100644 index 8548c34..0000000 --- a/dhparam.pem.default +++ /dev/null @@ -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----- diff --git a/dhparam/ffdhe2048.pem b/dhparam/ffdhe2048.pem new file mode 100644 index 0000000..088f967 --- /dev/null +++ b/dhparam/ffdhe2048.pem @@ -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----- \ No newline at end of file diff --git a/dhparam/ffdhe3072.pem b/dhparam/ffdhe3072.pem new file mode 100644 index 0000000..603f529 --- /dev/null +++ b/dhparam/ffdhe3072.pem @@ -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----- \ No newline at end of file diff --git a/dhparam/ffdhe4096.pem b/dhparam/ffdhe4096.pem new file mode 100644 index 0000000..eed4c41 --- /dev/null +++ b/dhparam/ffdhe4096.pem @@ -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----- \ No newline at end of file diff --git a/docker-compose-separate-containers.yml b/docker-compose-separate-containers.yml index a4edb94..254b742 100644 --- a/docker-compose-separate-containers.yml +++ b/docker-compose-separate-containers.yml @@ -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: diff --git a/docker-compose.yml b/docker-compose.yml index b76f0c0..138f396 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,7 +1,7 @@ version: '2' services: nginx-proxy: - image: jwilder/nginx-proxy + image: nginxproxy/nginx-proxy container_name: nginx-proxy ports: - "80:80" diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh index b425dfe..8f4ed7a 100755 --- a/docker-entrypoint.sh +++ b/docker-entrypoint.sh @@ -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 jwilder/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 2048 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 "$@" diff --git a/generate-dhparam.sh b/generate-dhparam.sh deleted file mode 100755 index 03b828c..0000000 --- a/generate-dhparam.sh +++ /dev/null @@ -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 diff --git a/nginx.tmpl b/nginx.tmpl index b56e3c9..e8e36ac 100644 --- a/nginx.tmpl +++ b/nginx.tmpl @@ -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,26 +263,39 @@ 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 }}; {{ end }} {{ $access_log }} - + # Do not HTTPS redirect Let'sEncrypt ACME challenge - location /.well-known/acme-challenge/ { + location ^~ /.well-known/acme-challenge/ { auth_basic off; + auth_request off; allow all; root /usr/share/nginx/html; try_files $uri =404; break; } - + location / { {{ if (hasPrefix "www." $host) }} - return 301 https://{{ trimPrefix "www." $host }}$request_uri; - {{ else }} + # Redirect www. to non-www. + {{ $trimmedHost := trimPrefix "www." $host }} + {{ if eq $external_https_port "443" }} + return 301 https://{{ $trimmedHost }}$request_uri; + {{ else }} + return 301 https://{{ $trimmedHost }}:{{ $external_https_port }}$request_uri; + {{ end }} + {{ end }} + {{ if eq $external_https_port "443" }} return 301 https://$host$request_uri; + {{ else }} + return 301 https://$host:{{ $external_https_port }}$request_uri; {{ end }} } } @@ -273,6 +303,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 }}; @@ -349,6 +382,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 }}; @@ -398,6 +434,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 }}; diff --git a/test/README.md b/test/README.md index 9d7a57c..99d16db 100644 --- a/test/README.md +++ b/test/README.md @@ -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 jwilder/nginx-proxy:test .. + make build-nginx-proxy-test-debian or if you want to test the alpine flavor: - docker build -t jwilder/nginx-proxy:test -f Dockerfile.alpine .. - -make sure to tag that test image exactly `jwilder/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,11 +56,11 @@ 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: -Any domain name containing the substring `nginx-proxy` will resolve to the IP address of the container that was created from the `jwilder/nginx-proxy:test` image. So all the following domain names will resolve to the nginx-proxy container in tests: +Any domain name containing the substring `nginx-proxy` will resolve to the IP address of the container that was created from the `nginxproxy/nginx-proxy:test` image. So all the following domain names will resolve to the nginx-proxy container in tests: - `nginx-proxy` - `nginx-proxy.com` - `www.nginx-proxy.com` @@ -99,9 +94,8 @@ 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 -If you need to create server certificates, use the [`certs/create_server_certificate.sh`](certs/) script. Pytest will be able to validate any certificate issued from this script. \ No newline at end of file +If you need to create server certificates, use the [`certs/create_server_certificate.sh`](certs/) script. Pytest will be able to validate any certificate issued from this script. diff --git a/test/certs/create_server_certificate.sh b/test/certs/create_server_certificate.sh index 0eb3201..2871609 100755 --- a/test/certs/create_server_certificate.sh +++ b/test/certs/create_server_certificate.sh @@ -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 diff --git a/test/conftest.py b/test/conftest.py index 6bd172a..cf26b30 100644 --- a/test/conftest.py +++ b/test/conftest.py @@ -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,17 +23,20 @@ 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' + ############################################################################### -# +# # utilities -# +# ############################################################################### @contextlib.contextmanager @@ -55,7 +60,7 @@ def ipv6(force_ipv6=True): class requests_for_docker(object): """ - Proxy for calling methods of the requests module. + Proxy for calling methods of the requests module. When a HTTP response failed due to HTTP Error 404 or 502, retry a few times. Provides method `get_conf` to extract the nginx-proxy configuration content. """ @@ -64,17 +69,32 @@ class requests_for_docker(object): if os.path.isfile(CA_ROOT_CERTIFICATE): self.session.verify = CA_ROOT_CERTIFICATE + @staticmethod + def get_nginx_proxy_containers() -> List[Container]: + """ + 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 = docker_client.containers.list(filters={"ancestor": "jwilder/nginx-proxy:test"}) - if len(nginx_proxy_containers) > 1: - pytest.fail("Too many running jwilder/nginx-proxy:test containers", pytrace=False) - elif len(nginx_proxy_containers) == 0: - pytest.fail("No running jwilder/nginx-proxy:test container", pytrace=False) + 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,27 +175,27 @@ 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"] def nginx_proxy_dns_resolver(domain_name): """ if "nginx-proxy" if found in host, return the ip address of the docker container - issued from the docker image jwilder/nginx-proxy:test. + issued from the docker image nginxproxy/nginx-proxy:test. :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": "jwilder/nginx-proxy:test"}) + 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 jwilder/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,39 +206,44 @@ 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\.docker$', domain_name) + match = re.search(r'(^|.+\.)(?P[^.]+)\.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)) - return ip + log.info(f"resolving domain name {domain_name!r} as IP address {ip} of container {container.name}") + return ip def monkey_patch_urllib_dns_resolver(): """ Alter the behavior of the urllib DNS resolver so that any domain name containing substring 'nginx-proxy' will resolve to the IP address - of the container created from image 'jwilder/nginx-proxy:test'. + of the container created from image 'nginxproxy/nginx-proxy:test'. """ 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,40 +278,43 @@ 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(): """ - If one (and only one) container started from image jwilder/nginx-proxy:test is found, + If one (and only one) container started from image nginxproxy/nginx-proxy:test is found, wait for its log to contain substring "Watching docker events" """ - containers = docker_client.containers.list(filters={"ancestor": "jwilder/nginx-proxy:test"}) + containers = docker_client.containers.list(filters={"ancestor": "nginxproxy/nginx-proxy:test"}) if len(containers) != 1: 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,27 +407,27 @@ 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] ############################################################################### -# +# # Py.test fixtures -# +# ############################################################################### -@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 - + A custom docker compose file name can be defined in a variable named `docker_compose_file`. - + Also, in the case where pytest is running from a docker container, this fixture makes sure our container will be attached to all the docker networks. """ @@ -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: @@ -430,16 +463,16 @@ def nginxproxy(): ############################################################################### -# +# # Py.test hooks -# +# ############################################################################### # pytest hook to display additionnal stuff in test report def pytest_runtest_logreport(report): if report.failed: if isinstance(report.longrepr, ReprExceptionInfo): - test_containers = docker_client.containers.list(all=True, filters={"ancestor": "jwilder/nginx-proxy:test"}) + test_containers = docker_client.containers.list(all=True, filters={"ancestor": "nginxproxy/nginx-proxy:test"}) for container in test_containers: report.longrepr.addsection('nginx-proxy logs', container.logs()) report.longrepr.addsection('nginx-proxy conf', get_nginx_conf_from_container(container)) @@ -456,18 +489,18 @@ 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})") ############################################################################### -# +# # Check requirements -# +# ############################################################################### try: - docker_client.images.get('jwilder/nginx-proxy:test') + docker_client.images.get('nginxproxy/nginx-proxy:test') except docker.errors.ImageNotFound: - pytest.exit("The docker image 'jwilder/nginx-proxy:test' is missing") + 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") diff --git a/test/lib/ssl/dhparam.pem b/test/lib/ssl/dhparam.pem deleted file mode 100644 index eb3218c..0000000 --- a/test/lib/ssl/dhparam.pem +++ /dev/null @@ -1,8 +0,0 @@ ------BEGIN DH PARAMETERS----- -MIIBCAKCAQEA1cae6HqPSgicEuAuSCf6Ii3d6qMX9Ta8lnwoX0JQ0CWK7mzaiiIi -dY7oHmc4cq0S3SH+g0tdLP9yqygFS9hdUGINwS2VV6poj2/vdL/dUshegyxpEH58 -nofCPnFDeKkcPDMYAlGS8zjp60TsBkRJKcrxxwnjod1Q5mWuMN5KH3sxs842udKH -0nHFE9kKW/NfXb+EGsjpocGpf786cGuCO2d00THsoItOEcM9/aI8DX1QcyxAHR6D -HaYTFJnyyx8Q44u27M15idI4pbNoKORlotiuOwCTGYCfbN14aOV+Ict7aSF8FWpP -48j9SMNuIu2DlF9pNLo6fsrOjYY3c9X12wIBAg== ------END DH PARAMETERS----- diff --git a/test/pytest.ini b/test/pytest.ini index 30f3e19..9ca7667 100644 --- a/test/pytest.ini +++ b/test/pytest.ini @@ -1,3 +1,5 @@ [pytest] # disable the creation of the `.cache` folders -addopts = -p no:cacheprovider --ignore=requirements --ignore=certs -r s -v \ No newline at end of file +addopts = -p no:cacheprovider --ignore=requirements --ignore=certs -r s -v +markers = + incremental: mark a test as incremental. \ No newline at end of file diff --git a/test/pytest.sh b/test/pytest.sh index 7d90b69..28275e5 100755 --- a/test/pytest.sh +++ b/test/pytest.sh @@ -8,17 +8,18 @@ # # ############################################################################### +# 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. -exec docker run --rm \ - -v ${DIR}:/${DIR} \ - -w ${DIR} \ - -v /var/run/docker.sock:/var/run/docker.sock \ - nginx-proxy-tester ${ARGS} +exec docker run --rm -it --name "nginx-proxy-pytest" \ + --volume "/var/run/docker.sock:/var/run/docker.sock" \ + --volume "${DIR}:${DIR}" \ + --workdir "${DIR}" \ + nginx-proxy-tester "${ARGS[@]}" \ No newline at end of file diff --git a/test/requirements/Dockerfile-nginx-proxy-tester b/test/requirements/Dockerfile-nginx-proxy-tester index 27d0538..36984fe 100644 --- a/test/requirements/Dockerfile-nginx-proxy-tester +++ b/test/requirements/Dockerfile-nginx-proxy-tester @@ -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 diff --git a/test/requirements/README.md b/test/requirements/README.md index 3a0c389..394c9b1 100644 --- a/test/requirements/README.md +++ b/test/requirements/README.md @@ -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 diff --git a/test/requirements/build.sh b/test/requirements/build.sh deleted file mode 100755 index f29897a..0000000 --- a/test/requirements/build.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash -set -e - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" - -docker build -t web $DIR/web \ No newline at end of file diff --git a/test/requirements/python-requirements.txt b/test/requirements/python-requirements.txt index ba95455..3747455 100644 --- a/test/requirements/python-requirements.txt +++ b/test/requirements/python-requirements.txt @@ -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 diff --git a/test/requirements/web/webserver.py b/test/requirements/web/webserver.py index 9334657..b8e81c0 100755 --- a/test/requirements/web/webserver.py +++ b/test/requirements/web/webserver.py @@ -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 diff --git a/test/stress_tests/test_deleted_cert/docker-compose.yml b/test/stress_tests/test_deleted_cert/docker-compose.yml index 06a61b9..33c92a7 100644 --- a/test/stress_tests/test_deleted_cert/docker-compose.yml +++ b/test/stress_tests/test_deleted_cert/docker-compose.yml @@ -8,7 +8,7 @@ web: reverseproxy: - image: jwilder/nginx-proxy:test + image: nginxproxy/nginx-proxy:test container_name: reverseproxy environment: DEBUG: "true" diff --git a/test/stress_tests/test_deleted_cert/test_restart_while_missing_cert.py b/test/stress_tests/test_deleted_cert/test_restart_while_missing_cert.py index 2b74acd..d7e4cbb 100644 --- a/test/stress_tests/test_deleted_cert/test_restart_while_missing_cert.py +++ b/test/stress_tests/test_deleted_cert/test_restart_while_missing_cert.py @@ -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 diff --git a/test/stress_tests/test_unreachable_network/README.md b/test/stress_tests/test_unreachable_network/README.md index aa09c4d..550b289 100644 --- a/test/stress_tests/test_unreachable_network/README.md +++ b/test/stress_tests/test_unreachable_network/README.md @@ -6,7 +6,7 @@ Furthermore, if the nginx-proxy in such state is restarted, the nginx process wi In the generated nginx config file, we can notice the presence of an empty `upstream {}` block. -This can be fixed by merging [PR-585](https://github.com/jwilder/nginx-proxy/pull/585). +This can be fixed by merging [PR-585](https://github.com/nginx-proxy/nginx-proxy/pull/585). ## How to reproduce diff --git a/test/stress_tests/test_unreachable_network/docker-compose.yml b/test/stress_tests/test_unreachable_network/docker-compose.yml index 0ca4f99..9666d29 100644 --- a/test/stress_tests/test_unreachable_network/docker-compose.yml +++ b/test/stress_tests/test_unreachable_network/docker-compose.yml @@ -9,7 +9,7 @@ services: container_name: reverseproxy networks: - netA - image: jwilder/nginx-proxy:test + image: nginxproxy/nginx-proxy:test volumes: - /var/run/docker.sock:/tmp/docker.sock:ro diff --git a/test/stress_tests/test_unreachable_network/test_unreachable_net.py b/test/stress_tests/test_unreachable_network/test_unreachable_net.py index dbcfb14..4c09da2 100644 --- a/test/stress_tests/test_unreachable_network/test_unreachable_net.py +++ b/test/stress_tests/test_unreachable_network/test_unreachable_net.py @@ -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) diff --git a/test/test_DOCKER_HOST_unix_socket.yml b/test/test_DOCKER_HOST_unix_socket.yml index dff75a8..1563872 100644 --- a/test/test_DOCKER_HOST_unix_socket.yml +++ b/test/test_DOCKER_HOST_unix_socket.yml @@ -16,9 +16,8 @@ web2: sut: - image: jwilder/nginx-proxy:test + 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 diff --git a/test/test_composev2.yml b/test/test_composev2.yml index ef4df8d..4a0c9fa 100644 --- a/test/test_composev2.yml +++ b/test/test_composev2.yml @@ -1,10 +1,9 @@ version: '2' services: nginx-proxy: - image: jwilder/nginx-proxy:test + 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 diff --git a/test/test_custom/test_defaults-location.yml b/test/test_custom/test_defaults-location.yml index a5b0c44..8b185f7 100644 --- a/test/test_custom/test_defaults-location.yml +++ b/test/test_custom/test_defaults-location.yml @@ -1,8 +1,7 @@ nginx-proxy: - image: jwilder/nginx-proxy:test + 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 diff --git a/test/test_custom/test_defaults.yml b/test/test_custom/test_defaults.yml index 2cfddf0..6086f40 100644 --- a/test/test_custom/test_defaults.yml +++ b/test/test_custom/test_defaults.yml @@ -1,10 +1,9 @@ version: '2' services: nginx-proxy: - image: jwilder/nginx-proxy:test + 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: diff --git a/test/test_custom/test_location-per-vhost.py b/test/test_custom/test_location-per-vhost.py index b99996e..f67b501 100644 --- a/test/test_custom/test_location-per-vhost.py +++ b/test/test_custom/test_location-per-vhost.py @@ -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() \ No newline at end of file + assert b"include /etc/nginx/vhost.d/web1.nginx-proxy.local_location;" in nginxproxy.get_conf() \ No newline at end of file diff --git a/test/test_custom/test_location-per-vhost.yml b/test/test_custom/test_location-per-vhost.yml index 988181c..99f31f3 100644 --- a/test/test_custom/test_location-per-vhost.yml +++ b/test/test_custom/test_location-per-vhost.yml @@ -1,10 +1,9 @@ version: '2' services: nginx-proxy: - image: jwilder/nginx-proxy:test + 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: diff --git a/test/test_custom/test_per-vhost.yml b/test/test_custom/test_per-vhost.yml index 61ae02b..5eba9f6 100644 --- a/test/test_custom/test_per-vhost.yml +++ b/test/test_custom/test_per-vhost.yml @@ -1,10 +1,9 @@ version: '2' services: nginx-proxy: - image: jwilder/nginx-proxy:test + 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: diff --git a/test/test_custom/test_proxy-wide.yml b/test/test_custom/test_proxy-wide.yml index 602f344..0cd6c40 100644 --- a/test/test_custom/test_proxy-wide.yml +++ b/test/test_custom/test_proxy-wide.yml @@ -1,10 +1,9 @@ version: '2' services: nginx-proxy: - image: jwilder/nginx-proxy:test + 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: diff --git a/test/test_debug/test_proxy-debug-flag.py b/test/test_debug/test_proxy-debug-flag.py new file mode 100644 index 0000000..af7f73a --- /dev/null +++ b/test/test_debug/test_proxy-debug-flag.py @@ -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 diff --git a/test/test_debug/test_proxy-debug-flag.yml b/test/test_debug/test_proxy-debug-flag.yml new file mode 100644 index 0000000..f930da3 --- /dev/null +++ b/test/test_debug/test_proxy-debug-flag.yml @@ -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" diff --git a/test/test_debug/test_server-debug-flag.py b/test/test_debug/test_server-debug-flag.py new file mode 100644 index 0000000..50ae737 --- /dev/null +++ b/test/test_debug/test_server-debug-flag.py @@ -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 diff --git a/test/test_debug/test_server-debug-flag.yml b/test/test_debug/test_server-debug-flag.yml new file mode 100644 index 0000000..89bb6b5 --- /dev/null +++ b/test/test_debug/test_server-debug-flag.yml @@ -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 diff --git a/test/test_default-host.yml b/test/test_default-host.yml index f195f58..2cb94d9 100644 --- a/test/test_default-host.yml +++ b/test/test_default-host.yml @@ -10,9 +10,8 @@ web1: # WHEN nginx-proxy runs with DEFAULT_HOST set to web1.tld sut: - image: jwilder/nginx-proxy:test + 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 diff --git a/test/test_dockergen/test_dockergen_v2.py b/test/test_dockergen/test_dockergen_v2.py index c797d0c..43b1431 100644 --- a/test/test_dockergen/test_dockergen_v2.py +++ b/test/test_dockergen/test_dockergen_v2.py @@ -4,23 +4,27 @@ 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 - the jwilder/nginx-proxy:test image + the nginxproxy/nginx-proxy:test image """ script_dir = os.path.dirname(__file__) - logging.info("extracting nginx.tmpl from jwilder/nginx-proxy:test") + logging.info("extracting nginx.tmpl from nginxproxy/nginx-proxy:test") docker_client = docker.from_env() - print(docker_client.containers.run( - image='jwilder/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" diff --git a/test/test_dockergen/test_dockergen_v2.yml b/test/test_dockergen/test_dockergen_v2.yml index 0fc8af5..b1f443c 100644 --- a/test/test_dockergen/test_dockergen_v2.yml +++ b/test/test_dockergen/test_dockergen_v2.yml @@ -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 diff --git a/test/test_dockergen/test_dockergen_v3.py b/test/test_dockergen/test_dockergen_v3.py index 808949b..67561bf 100644 --- a/test/test_dockergen/test_dockergen_v3.py +++ b/test/test_dockergen/test_dockergen_v3.py @@ -3,47 +3,37 @@ 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 - the jwilder/nginx-proxy:test image + the nginxproxy/nginx-proxy:test image """ script_dir = os.path.dirname(__file__) - logging.info("extracting nginx.tmpl from jwilder/nginx-proxy:test") + logging.info("extracting nginx.tmpl from nginxproxy/nginx-proxy:test") docker_client = docker.from_env() - print(docker_client.containers.run( - image='jwilder/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() diff --git a/test/test_dockergen/test_dockergen_v3.yml b/test/test_dockergen/test_dockergen_v3.yml index fad145a..8339273 100644 --- a/test/test_dockergen/test_dockergen_v3.yml +++ b/test/test_dockergen/test_dockergen_v3.yml @@ -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 diff --git a/test/test_events.py b/test/test_events.py index fa97f84..201917f 100644 --- a/test/test_events.py +++ b/test/test_events.py @@ -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. diff --git a/test/test_events.yml b/test/test_events.yml index 87b7c01..260529e 100644 --- a/test/test_events.yml +++ b/test/test_events.yml @@ -1,5 +1,4 @@ nginxproxy: - image: jwilder/nginx-proxy:test + image: nginxproxy/nginx-proxy:test volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - - ./lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro diff --git a/test/test_headers/certs/web-server-tokens-off.nginx-proxy.tld.crt b/test/test_headers/certs/web-server-tokens-off.nginx-proxy.tld.crt new file mode 100644 index 0000000..a96109a --- /dev/null +++ b/test/test_headers/certs/web-server-tokens-off.nginx-proxy.tld.crt @@ -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----- diff --git a/test/test_headers/certs/web-server-tokens-off.nginx-proxy.tld.key b/test/test_headers/certs/web-server-tokens-off.nginx-proxy.tld.key new file mode 100644 index 0000000..4e87ba8 --- /dev/null +++ b/test/test_headers/certs/web-server-tokens-off.nginx-proxy.tld.key @@ -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----- diff --git a/test/test_headers/test_http.py b/test/test_headers/test_http.py index 2799262..5983a10 100644 --- a/test/test_headers/test_http.py +++ b/test/test_headers/test_http.py @@ -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 @@ -78,4 +76,24 @@ def test_httpoxy_safe(docker_compose, nginxproxy): r = nginxproxy.get("http://web.nginx-proxy.tld/headers", headers={'Proxy': 'tcp://some.hacker.com'}) 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" diff --git a/test/test_headers/test_http.yml b/test/test_headers/test_http.yml index 8cc2e09..93795dc 100644 --- a/test/test_headers/test_http.yml +++ b/test/test_headers/test_http.yml @@ -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: jwilder/nginx-proxy:test + image: nginxproxy/nginx-proxy:test volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - - ../lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro diff --git a/test/test_headers/test_https.py b/test/test_headers/test_https.py index a1d434a..c5457c4 100644 --- a/test/test_headers/test_https.py +++ b/test/test_headers/test_https.py @@ -79,4 +79,25 @@ def test_httpoxy_safe(docker_compose, nginxproxy): r = nginxproxy.get("https://web.nginx-proxy.tld/headers", headers={'Proxy': 'tcp://some.hacker.com'}) 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" diff --git a/test/test_headers/test_https.yml b/test/test_headers/test_https.yml index 131f61c..49dcec4 100644 --- a/test/test_headers/test_https.yml +++ b/test/test_headers/test_https.yml @@ -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: jwilder/nginx-proxy:test + 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 diff --git a/test/test_http_port.py b/test/test_http_port.py new file mode 100644 index 0000000..26302c5 --- /dev/null +++ b/test/test_http_port.py @@ -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 \ No newline at end of file diff --git a/test/test_http_port.yml b/test/test_http_port.yml new file mode 100644 index 0000000..72f142f --- /dev/null +++ b/test/test_http_port.yml @@ -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 \ No newline at end of file diff --git a/test/test_ipv6.yml b/test/test_ipv6.yml index a0b504e..4dce515 100644 --- a/test/test_ipv6.yml +++ b/test/test_ipv6.yml @@ -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: jwilder/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 diff --git a/test/test_multiple-hosts.yml b/test/test_multiple-hosts.yml index 70269c8..b72da83 100644 --- a/test/test_multiple-hosts.yml +++ b/test/test_multiple-hosts.yml @@ -8,7 +8,6 @@ web: sut: - image: jwilder/nginx-proxy:test + image: nginxproxy/nginx-proxy:test volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - - ./lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro diff --git a/test/test_multiple-networks.yml b/test/test_multiple-networks.yml index da3277b..e4548b5 100644 --- a/test/test_multiple-networks.yml +++ b/test/test_multiple-networks.yml @@ -6,10 +6,9 @@ networks: services: nginx-proxy: - image: jwilder/nginx-proxy:test + 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 diff --git a/test/test_multiple-ports/test_VIRTUAL_PORT-single-different-from-single-port.py b/test/test_multiple-ports/test_VIRTUAL_PORT-single-different-from-single-port.py new file mode 100644 index 0000000..4008166 --- /dev/null +++ b/test/test_multiple-ports/test_VIRTUAL_PORT-single-different-from-single-port.py @@ -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')) diff --git a/test/test_multiple-ports/test_VIRTUAL_PORT-single-different-from-single-port.yml b/test/test_multiple-ports/test_VIRTUAL_PORT-single-different-from-single-port.yml new file mode 100644 index 0000000..dff6212 --- /dev/null +++ b/test/test_multiple-ports/test_VIRTUAL_PORT-single-different-from-single-port.yml @@ -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 diff --git a/test/test_multiple-ports/test_VIRTUAL_PORT.yml b/test/test_multiple-ports/test_VIRTUAL_PORT.yml index 4eb95ea..1a3ecaa 100644 --- a/test/test_multiple-ports/test_VIRTUAL_PORT.yml +++ b/test/test_multiple-ports/test_VIRTUAL_PORT.yml @@ -9,7 +9,6 @@ web: VIRTUAL_PORT: 90 sut: - image: jwilder/nginx-proxy:test + image: nginxproxy/nginx-proxy:test volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - - ../lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro diff --git a/test/test_multiple-ports/test_default-80.yml b/test/test_multiple-ports/test_default-80.yml index f06ccb8..10047dc 100644 --- a/test/test_multiple-ports/test_default-80.yml +++ b/test/test_multiple-ports/test_default-80.yml @@ -8,7 +8,6 @@ web: VIRTUAL_HOST: "web.nginx-proxy.tld" sut: - image: jwilder/nginx-proxy:test + image: nginxproxy/nginx-proxy:test volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - - ../lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro diff --git a/test/test_multiple-ports/test_single-port-not-80.yml b/test/test_multiple-ports/test_single-port-not-80.yml index 15f230a..18b3655 100644 --- a/test/test_multiple-ports/test_single-port-not-80.yml +++ b/test/test_multiple-ports/test_single-port-not-80.yml @@ -8,7 +8,6 @@ web: sut: - image: jwilder/nginx-proxy:test + image: nginxproxy/nginx-proxy:test volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - - ../lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro diff --git a/test/test_nominal.py b/test/test_nominal.py index cce7c94..a3f9c87 100644 --- a/test/test_nominal.py +++ b/test/test_nominal.py @@ -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 diff --git a/test/test_nominal.yml b/test/test_nominal.yml index d436499..fe02034 100644 --- a/test/test_nominal.yml +++ b/test/test_nominal.yml @@ -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: jwilder/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 diff --git a/test/test_raw-ip-vhost.py b/test/test_raw-ip-vhost.py new file mode 100644 index 0000000..aaff852 --- /dev/null +++ b/test/test_raw-ip-vhost.py @@ -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" diff --git a/test/test_raw-ip-vhost.yml b/test/test_raw-ip-vhost.yml new file mode 100644 index 0000000..066dade --- /dev/null +++ b/test/test_raw-ip-vhost.yml @@ -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 diff --git a/test/test_server-down/test_load-balancing.py b/test/test_server-down/test_load-balancing.py new file mode 100644 index 0000000..b65d0a1 --- /dev/null +++ b/test/test_server-down/test_load-balancing.py @@ -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 diff --git a/test/test_server-down/test_load-balancing.yml b/test/test_server-down/test_load-balancing.yml new file mode 100644 index 0000000..d420072 --- /dev/null +++ b/test/test_server-down/test_load-balancing.yml @@ -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 diff --git a/test/test_server-down/test_no-server-down.py b/test/test_server-down/test_no-server-down.py new file mode 100644 index 0000000..a98ed56 --- /dev/null +++ b/test/test_server-down/test_no-server-down.py @@ -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 diff --git a/test/test_server-down/test_no-server-down.yml b/test/test_server-down/test_no-server-down.yml new file mode 100644 index 0000000..b3d4629 --- /dev/null +++ b/test/test_server-down/test_no-server-down.yml @@ -0,0 +1,12 @@ +web: + image: web + expose: + - "81" + environment: + WEB_PORTS: 81 + VIRTUAL_HOST: web.nginx-proxy.tld + +sut: + image: nginxproxy/nginx-proxy:test + volumes: + - /var/run/docker.sock:/tmp/docker.sock:ro diff --git a/test/test_server-down/test_server-down.py b/test/test_server-down/test_server-down.py new file mode 100644 index 0000000..995cd7d --- /dev/null +++ b/test/test_server-down/test_server-down.py @@ -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 diff --git a/test/test_server-down/test_server-down.yml b/test/test_server-down/test_server-down.yml new file mode 100644 index 0000000..938d26a --- /dev/null +++ b/test/test_server-down/test_server-down.yml @@ -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 diff --git a/test/test_ssl/certs/web2.nginx-proxy.tld.dhparam.pem b/test/test_ssl/certs/web2.nginx-proxy.tld.dhparam.pem new file mode 100644 index 0000000..088f967 --- /dev/null +++ b/test/test_ssl/certs/web2.nginx-proxy.tld.dhparam.pem @@ -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----- \ No newline at end of file diff --git a/test/test_ssl/test_dhparam.py b/test/test_ssl/test_dhparam.py index 40339a1..2f69ad3 100644 --- a/test/test_ssl/test_dhparam.py +++ b/test/test_ssl/test_dhparam.py @@ -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 diff --git a/test/test_ssl/test_dhparam.yml b/test/test_ssl/test_dhparam.yml index 66b1a61..fa4fe1e 100644 --- a/test/test_ssl/test_dhparam.yml +++ b/test/test_ssl/test_dhparam.yml @@ -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: jwilder/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 diff --git a/test/test_ssl/test_dhparam_generation.py b/test/test_ssl/test_dhparam_generation.py deleted file mode 100644 index 1e5d154..0000000 --- a/test/test_ssl/test_dhparam_generation.py +++ /dev/null @@ -1,44 +0,0 @@ -import backoff -import docker - -docker_client = docker.from_env() - - -############################################################################### -# -# Tests helpers -# -############################################################################### - -@backoff.on_exception(backoff.constant, AssertionError, interval=2, max_tries=15, jitter=None) -def assert_log_contains(expected_log_line): - """ - 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. - - :param expected_log_line: string to search for - :return: None - :raises: AssertError if the expected string is not found in the log - """ - sut_container = docker_client.containers.get("nginxproxy") - docker_logs = sut_container.logs(stdout=True, stderr=True, stream=False, follow=False) - assert expected_log_line in docker_logs - - -############################################################################### -# -# Tests -# -############################################################################### - -def test_dhparam_is_generated_if_missing(docker_compose): - sut_container = docker_client.containers.get("nginxproxy") - assert sut_container.status == "running" - - assert_log_contains("A pre-generated dhparam.pem will be used for now") - assert_log_contains("dhparam generation complete, reloading nginx") - - # 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() - generated_checksum = sut_container.exec_run("md5sum /etc/nginx/dhparam/dhparam.pem").split() - assert default_checksum[0] != generated_checksum[0] diff --git a/test/test_ssl/test_dhparam_generation.yml b/test/test_ssl/test_dhparam_generation.yml deleted file mode 100644 index 35f3067..0000000 --- a/test/test_ssl/test_dhparam_generation.yml +++ /dev/null @@ -1,8 +0,0 @@ -sut: - image: jwilder/nginx-proxy:test - container_name: nginxproxy - volumes: - - /var/run/docker.sock:/tmp/docker.sock:ro - - ./certs:/etc/nginx/certs:ro - environment: - - DHPARAM_BITS=256 diff --git a/test/test_ssl/test_hsts.py b/test/test_ssl/test_hsts.py index 12bbcc4..16dffd2 100644 --- a/test/test_ssl/test_hsts.py +++ b/test/test_ssl/test_hsts.py @@ -8,7 +8,7 @@ def test_web1_HSTS_default(docker_compose, nginxproxy): assert "max-age=31536000" == r.headers["Strict-Transport-Security"] # Regression test to ensure HSTS is enabled even when the upstream sends an error in response -# Issue #1073 https://github.com/jwilder/nginx-proxy/pull/1073 +# Issue #1073 https://github.com/nginx-proxy/nginx-proxy/pull/1073 def test_web1_HSTS_error(docker_compose, nginxproxy): r = nginxproxy.get("https://web1.nginx-proxy.tld/status/500", allow_redirects=False) assert "Strict-Transport-Security" in r.headers @@ -26,7 +26,7 @@ def test_web3_HSTS_custom(docker_compose, nginxproxy): assert "max-age=86400; includeSubDomains; preload" == r.headers["Strict-Transport-Security"] # Regression test for issue 1080 -# https://github.com/jwilder/nginx-proxy/issues/1080 +# https://github.com/nginx-proxy/nginx-proxy/issues/1080 def test_web4_HSTS_off_noredirect(docker_compose, nginxproxy): r = nginxproxy.get("https://web4.nginx-proxy.tld/port", allow_redirects=False) assert "answer from port 81\n" in r.text diff --git a/test/test_ssl/test_hsts.yml b/test/test_ssl/test_hsts.yml index f6f39a7..b4af3b6 100644 --- a/test/test_ssl/test_hsts.yml +++ b/test/test_ssl/test_hsts.yml @@ -35,8 +35,7 @@ web4: HTTPS_METHOD: "noredirect" sut: - image: jwilder/nginx-proxy:test + 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 diff --git a/test/test_ssl/test_https_port.py b/test/test_ssl/test_https_port.py new file mode 100644 index 0000000..214d4d9 --- /dev/null +++ b/test/test_ssl/test_https_port.py @@ -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 \ No newline at end of file diff --git a/test/test_ssl/test_https_port.yml b/test/test_ssl/test_https_port.yml new file mode 100644 index 0000000..7b674d7 --- /dev/null +++ b/test/test_ssl/test_https_port.yml @@ -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 \ No newline at end of file diff --git a/test/test_ssl/test_nohttp.yml b/test/test_ssl/test_nohttp.yml index 51d63c2..48a7aa3 100644 --- a/test/test_ssl/test_nohttp.yml +++ b/test/test_ssl/test_nohttp.yml @@ -9,8 +9,7 @@ web2: sut: - image: jwilder/nginx-proxy:test + 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 diff --git a/test/test_ssl/test_nohttps.yml b/test/test_ssl/test_nohttps.yml index 14140b4..3f3df19 100644 --- a/test/test_ssl/test_nohttps.yml +++ b/test/test_ssl/test_nohttps.yml @@ -9,7 +9,6 @@ web: sut: - image: jwilder/nginx-proxy:test + image: nginxproxy/nginx-proxy:test volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - - ../lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro diff --git a/test/test_ssl/test_noredirect.yml b/test/test_ssl/test_noredirect.yml index 9149a87..ecd93f6 100644 --- a/test/test_ssl/test_noredirect.yml +++ b/test/test_ssl/test_noredirect.yml @@ -9,8 +9,7 @@ web3: sut: - image: jwilder/nginx-proxy:test + 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 diff --git a/test/test_ssl/test_wildcard.py b/test/test_ssl/test_wildcard.py index 9885d94..202ba24 100644 --- a/test/test_ssl/test_wildcard.py +++ b/test/test_ssl/test_wildcard.py @@ -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 diff --git a/test/test_ssl/test_wildcard.yml b/test/test_ssl/test_wildcard.yml index 4c77796..e1504ed 100644 --- a/test/test_ssl/test_wildcard.yml +++ b/test/test_ssl/test_wildcard.yml @@ -7,8 +7,7 @@ web1: VIRTUAL_HOST: "*.nginx-proxy.tld" sut: - image: jwilder/nginx-proxy:test + 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 diff --git a/test/test_ssl/wildcard_cert_and_nohttps/docker-compose.yml b/test/test_ssl/wildcard_cert_and_nohttps/docker-compose.yml index 20cd1b2..98f41a0 100644 --- a/test/test_ssl/wildcard_cert_and_nohttps/docker-compose.yml +++ b/test/test_ssl/wildcard_cert_and_nohttps/docker-compose.yml @@ -3,11 +3,10 @@ version: "3" services: proxy: - image: jwilder/nginx-proxy:test + image: nginxproxy/nginx-proxy:test 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 diff --git a/test/test_ssl/wildcard_cert_and_nohttps/test_wildcard_cert_nohttps.py b/test/test_ssl/wildcard_cert_and_nohttps/test_wildcard_cert_nohttps.py index 2808dee..68b0329 100644 --- a/test/test_ssl/wildcard_cert_and_nohttps/test_wildcard_cert_nohttps.py +++ b/test/test_ssl/wildcard_cert_and_nohttps/test_wildcard_cert_nohttps.py @@ -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") diff --git a/test/test_upstream-name/test_predictable-name.py b/test/test_upstream-name/test_predictable-name.py new file mode 100644 index 0000000..7e19646 --- /dev/null +++ b/test/test_upstream-name/test_predictable-name.py @@ -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) diff --git a/test/test_upstream-name/test_predictable-name.yml b/test/test_upstream-name/test_predictable-name.yml new file mode 100644 index 0000000..cd8d250 --- /dev/null +++ b/test/test_upstream-name/test_predictable-name.yml @@ -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 diff --git a/test/test_upstream-name/test_sha1-name.py b/test/test_upstream-name/test_sha1-name.py new file mode 100644 index 0000000..663ca28 --- /dev/null +++ b/test/test_upstream-name/test_sha1-name.py @@ -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" diff --git a/test/test_upstream-name/test_sha1-name.yml b/test/test_upstream-name/test_sha1-name.yml new file mode 100644 index 0000000..54989ae --- /dev/null +++ b/test/test_upstream-name/test_sha1-name.yml @@ -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" diff --git a/test/test_wildcard_host.py b/test/test_wildcard_host.py index eb8428e..a5b6633 100644 --- a/test/test_wildcard_host.py +++ b/test/test_wildcard_host.py @@ -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 diff --git a/test/test_wildcard_host.yml b/test/test_wildcard_host.yml index 742a8ac..b745e31 100644 --- a/test/test_wildcard_host.yml +++ b/test/test_wildcard_host.yml @@ -32,7 +32,6 @@ web4: sut: - image: jwilder/nginx-proxy:test + image: nginxproxy/nginx-proxy:test volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - - ./lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro diff --git a/test/test_www_redirect.yml b/test/test_www_redirect.yml index 29b9ea5..66da08a 100644 --- a/test/test_www_redirect.yml +++ b/test/test_www_redirect.yml @@ -19,9 +19,8 @@ https: # Proxy sut: - image: jwilder/nginx-proxy:test + image: nginxproxy/nginx-proxy:test volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - - ./lib/ssl/dhparam.pem:/etc/nginx/dhparam/dhparam.pem:ro - ./test_ssl/certs:/etc/nginx/certs:ro \ No newline at end of file