Optimize uwsgi-nginx

This commit is contained in:
Stille 2021-06-25 23:55:24 +08:00
parent bf4a29473d
commit b3a5c3ae92
51 changed files with 8 additions and 1161 deletions

View File

@ -9,16 +9,18 @@ on:
jobs:
build:
runs-on: ubuntu-latest
env:
ACTIONS_ALLOW_UNSECURE_COMMANDS: true
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Set tag
id: tag
run: |
TAG=$(cat ${{ env.PROJECT }}/docker-images/Dockerfile | awk 'NR==4 {print $3}')
echo "::set-env name=TAG::$TAG"
if [[ -n $(cat ${{ env.PROJECT }}/Dockerfile | awk '{if($2~"VERSION")print $3}') ]]; then
VERSION=$(cat ${{ env.PROJECT }}/Dockerfile | awk '{if($2~"VERSION")print $3}')
echo "tag=$VERSION" >> $GITHUB_ENV
else
echo "tag=$(date +%Y)-$(date +%m)-$(date +%d)" >> $GITHUB_ENV
fi
- name: Docker Hub login
env:
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
@ -37,6 +39,6 @@ jobs:
docker buildx build \
--platform=linux/amd64,linux/arm64 \
--output "type=image,push=true" \
--file ${{ env.PROJECT }}/docker-images/Dockerfile ./${{ env.PROJECT }}/docker-images \
--file ${{ env.PROJECT }}/Dockerfile ./${{ env.PROJECT }} \
--tag $(echo "${DOCKER_USERNAME}" | tr '[:upper:]' '[:lower:]')/${{ env.PROJECT }}:latest \
--tag $(echo "${DOCKER_USERNAME}" | tr '[:upper:]' '[:lower:]')/${{ env.PROJECT }}:${TAG}
--tag $(echo "${DOCKER_USERNAME}" | tr '[:upper:]' '[:lower:]')/${{ env.PROJECT }}:${{ env.tag }}

112
uwsgi-nginx/.gitignore vendored
View File

@ -1,112 +0,0 @@
### Python template
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
.mypy_cache
.vscode
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
# Translations
*.mo
*.pot
# Django stuff:
*.log
# Sphinx documentation
docs/_build/
# PyBuilder
target/
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio
*.iml
## Directory-based project format:
.idea/
# if you remove the above rule, at least ignore the following:
# User-specific stuff:
# .idea/workspace.xml
# .idea/tasks.xml
# .idea/dictionaries
# Sensitive or high-churn files:
# .idea/dataSources.ids
# .idea/dataSources.xml
# .idea/sqlDataSources.xml
# .idea/dynamic.xml
# .idea/uiDesigner.xml
# Gradle:
# .idea/gradle.xml
# .idea/libraries
# Mongo Explorer plugin:
# .idea/mongoSettings.xml
## File-based project format:
*.ipr
*.iws
## Plugin-specific files:
# IntelliJ
/out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
# Custom
Pipfile.lock
poetry.lock

View File

@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -1,41 +0,0 @@
dist: xenial
language: python
python:
- "3.7"
install:
- pip install docker pytest
services:
- docker
env:
- NAME='python2.7' BUILD_PATH='python2.7' TEST_STR1='Hello World from a default Nginx uWSGI Python 2.7 app in a Docker container (default)' TEST_STR2='Hello World from Nginx uWSGI Python 2.7 app in a Docker container' RUN_TESTS='1'
- NAME='python2.7-alpine3.7' BUILD_PATH='python2.7-alpine3.7' TEST_STR1='Hello World from a default Nginx uWSGI Python 2.7 app in a Docker container in Alpine (default)' TEST_STR2='Hello World from Nginx uWSGI Python 2.7 app in a Docker container' RUN_TESTS='1'
- NAME='python2.7-alpine3.8' BUILD_PATH='python2.7-alpine3.8' TEST_STR1='Hello World from a default Nginx uWSGI Python 2.7 app in a Docker container in Alpine (default)' TEST_STR2='Hello World from Nginx uWSGI Python 2.7 app in a Docker container' RUN_TESTS='1'
- NAME='python2.7-alpine3.9' BUILD_PATH='python2.7-alpine3.9' TEST_STR1='Hello World from a default Nginx uWSGI Python 2.7 app in a Docker container in Alpine (default)' TEST_STR2='Hello World from Nginx uWSGI Python 2.7 app in a Docker container' RUN_TESTS='1'
- NAME='python3.5' BUILD_PATH='python3.5' TEST_STR1='Hello World from a default Nginx uWSGI Python 3.5 app in a Docker container (default)' TEST_STR2='Hello World from Nginx uWSGI Python 3.5 app in a Docker container' RUN_TESTS='1'
- NAME='python3.6' BUILD_PATH='python3.6' TEST_STR1='Hello World from a default Nginx uWSGI Python 3.6 app in a Docker container (default)' TEST_STR2='Hello World from Nginx uWSGI Python 3.6 app in a Docker container' RUN_TESTS='1'
- NAME='python3.6-alpine3.7' BUILD_PATH='python3.6-alpine3.7' TEST_STR1='Hello World from a default Nginx uWSGI Python 3.6 app in a Docker container in Alpine (default)' TEST_STR2='Hello World from Nginx uWSGI Python 3.6 app in a Docker container' RUN_TESTS='1'
- NAME='python3.6-alpine3.8' BUILD_PATH='python3.6-alpine3.8' TEST_STR1='Hello World from a default Nginx uWSGI Python 3.6 app in a Docker container in Alpine (default)' TEST_STR2='Hello World from Nginx uWSGI Python 3.6 app in a Docker container' RUN_TESTS='1'
- NAME='python3.6-alpine3.9' BUILD_PATH='python3.6-alpine3.9' TEST_STR1='Hello World from a default Nginx uWSGI Python 3.6 app in a Docker container in Alpine (default)' TEST_STR2='Hello World from Nginx uWSGI Python 3.6 app in a Docker container' RUN_TESTS='1'
- NAME='python3.7' BUILD_PATH='python3.7' TEST_STR1='Hello World from a default Nginx uWSGI Python 3.7 app in a Docker container (default)' TEST_STR2='Hello World from Nginx uWSGI Python 3.7 app in a Docker container' RUN_TESTS='1'
- NAME='latest' BUILD_PATH='python3.7' TEST_STR1='Hello World from a default Nginx uWSGI Python 3.7 app in a Docker container (default)' TEST_STR2='Hello World from Nginx uWSGI Python 3.7 app in a Docker container' RUN_TESTS='1'
- NAME='python3.7-alpine3.7' BUILD_PATH='python3.7-alpine3.7' TEST_STR1='Hello World from a default Nginx uWSGI Python 3.7 app in a Docker container in Alpine (default)' TEST_STR2='Hello World from Nginx uWSGI Python 3.7 app in a Docker container' RUN_TESTS=''
- NAME='python3.7-alpine3.8' BUILD_PATH='python3.7-alpine3.8' TEST_STR1='Hello World from a default Nginx uWSGI Python 3.7 app in a Docker container in Alpine (default)' TEST_STR2='Hello World from Nginx uWSGI Python 3.7 app in a Docker container' RUN_TESTS=''
- NAME='python3.7-alpine3.9' BUILD_PATH='python3.7-alpine3.9' TEST_STR1='Hello World from a default Nginx uWSGI Python 3.7 app in a Docker container in Alpine (default)' TEST_STR2='Hello World from Nginx uWSGI Python 3.7 app in a Docker container' RUN_TESTS=''
script: bash scripts/test.sh
jobs:
include:
- script: bash scripts/test.sh
- stage: deploy
script: skip
deploy:
provider: script
script: bash scripts/build-push-all.sh
on:
branch: master

View File

@ -1,3 +0,0 @@
[mypy]
disallow_untyped_defs = True
ignore_missing_imports = True

View File

@ -1,21 +0,0 @@
[tool.poetry]
name = "uwsgi-nginx-docker"
version = "0.1.0"
description = "Docker image with uWSGI and Nginx for web applications in Python 3.6 and above and Python 2.7 (as Flask) in a single container. Optionally with Alpine Linux."
authors = ["Sebastián Ramírez <tiangolo@gmail.com>"]
license = "MIT"
[tool.poetry.dependencies]
python = "^3.6"
docker = "^4.2.0"
pytest = "^5.4.1"
[tool.poetry.dev-dependencies]
black = "^19.10b0"
isort = "^4.3.21"
autoflake = "^1.3.1"
mypy = "^0.770"
[build-system]
requires = ["poetry>=0.12"]
build-backend = "poetry.masonry.api"

View File

@ -1,7 +0,0 @@
#!/usr/bin/env bash
set -e
bash scripts/docker-login.sh
BUILD_PUSH=1 python scripts/process_all.py

View File

@ -1,15 +0,0 @@
#!/usr/bin/env bash
set -e
use_tag="tiangolo/uwsgi-nginx:$NAME"
use_dated_tag="${use_tag}-$(date -I)"
bash scripts/build.sh
docker tag "$use_tag" "$use_dated_tag"
bash scripts/docker-login.sh
docker push "$use_tag"
docker push "$use_dated_tag"

View File

@ -1,12 +0,0 @@
#!/usr/bin/env bash
set -e
use_tag="tiangolo/uwsgi-nginx:$NAME"
DOCKERFILE="$NAME"
if [ "$NAME" == "latest" ] ; then
DOCKERFILE="python3.8"
fi
docker build -t "$use_tag" --file "./docker-images/${DOCKERFILE}.dockerfile" "./docker-images/"

View File

@ -1,5 +0,0 @@
#!/usr/bin/env bash
set -e
echo "$DOCKER_PASSWORD" | docker login -u "$DOCKER_USERNAME" --password-stdin

View File

@ -1,6 +0,0 @@
#!/usr/bin/env bash
set -x
# Sort imports one per line, so autoflake can remove unused imports
isort --recursive --force-single-line-imports --apply ./
sh ./scripts/format.sh

View File

@ -1,7 +0,0 @@
#!/usr/bin/env bash
set -x
autoflake --remove-all-unused-imports --recursive --remove-unused-variables --in-place ./ --exclude=__init__.py
isort --multi-line=3 --trailing-comma --force-grid-wrap=0 --combine-as --line-width 88 --recursive --apply ./
black ./

View File

@ -1,8 +0,0 @@
#!/usr/bin/env bash
set -e
set -x
mypy ./
black ./ --check
isort --multi-line=3 --trailing-comma --force-grid-wrap=0 --combine-as --line-width 88 --recursive --check-only

View File

@ -1,54 +0,0 @@
import os
import subprocess
import sys
environments = [
{"NAME": "latest", "PYTHON_VERSION": "3.8"},
{"NAME": "python3.8", "PYTHON_VERSION": "3.8"},
{"NAME": "python3.7", "PYTHON_VERSION": "3.7"},
{"NAME": "python3.6", "PYTHON_VERSION": "3.6"},
{"NAME": "python2.7", "PYTHON_VERSION": "2.7"},
{"NAME": "python3.8-alpine", "PYTHON_VERSION": "3.8"},
]
start_with = os.environ.get("START_WITH")
build_push = os.environ.get("BUILD_PUSH")
def process_tag(*, env: dict) -> None:
use_env = {**os.environ, **env}
script = "scripts/test.sh"
if build_push:
script = "scripts/build-push.sh"
return_code = subprocess.call(["bash", script], env=use_env)
if return_code != 0:
sys.exit(return_code)
def print_version_envs() -> None:
env_lines = []
for env in environments:
env_vars = []
for key, value in env.items():
env_vars.append(f"{key}='{value}'")
env_lines.append(" ".join(env_vars))
for line in env_lines:
print(line)
def main() -> None:
start_at = 0
if start_with:
start_at = [
i for i, env in enumerate((environments)) if env["NAME"] == start_with
][0]
for i, env in enumerate(environments[start_at:]):
print(f"Processing tag: {env['NAME']}")
process_tag(env=env)
if __name__ == "__main__":
if len(sys.argv) > 1:
print_version_envs()
else:
main()

View File

@ -1,4 +0,0 @@
#!/usr/bin/env bash
set -e
python scripts/process_all.py

View File

@ -1,5 +0,0 @@
#!/usr/bin/env bash
set -e
bash scripts/build.sh
pytest tests "$@"

View File

@ -1 +0,0 @@
Dockerfile

View File

@ -1,78 +0,0 @@
import os
import time
import docker
import requests
from docker.models.containers import Container
from requests import Response
from ..utils import (
CONTAINER_NAME,
get_logs,
get_nginx_config,
get_response_text1,
remove_previous_container,
)
client = docker.from_env()
def verify_container(container: Container, response_text: str) -> None:
response: Response = requests.get("http://127.0.0.1:8000")
assert response.text == response_text
nginx_config = get_nginx_config(container)
assert "client_max_body_size 0;" in nginx_config
assert "worker_processes 1;" in nginx_config
assert "listen 80;" in nginx_config
assert "worker_connections 1024;" in nginx_config
assert "worker_rlimit_nofile;" not in nginx_config
assert "daemon off;" in nginx_config
assert "include uwsgi_params;" in nginx_config
assert "uwsgi_pass unix:///tmp/uwsgi.sock;" in nginx_config
logs = get_logs(container)
assert "getting INI configuration from /app/uwsgi.ini" in logs
assert "getting INI configuration from /etc/uwsgi/uwsgi.ini" in logs
assert "ini = /app/uwsgi.ini" in logs
assert "ini = /etc/uwsgi/uwsgi.ini" in logs
assert "socket = /tmp/uwsgi.sock" in logs
assert "chown-socket = nginx:nginx" in logs
assert "chmod-socket = 664" in logs
assert "hook-master-start = unix_signal:15 gracefully_kill_them_all" in logs
assert "need-app = true" in logs
assert "die-on-term = true" in logs
assert "show-config = true" in logs
assert "wsgi-file = /app/main.py" in logs
assert "processes = 16" in logs
assert "cheaper = 2" in logs
assert "Checking for script in /app/prestart.sh" in logs
assert "Running script /app/prestart.sh" in logs
assert (
"Running inside /app/prestart.sh, you could add migrations to this file" in logs
)
assert "spawned uWSGI master process" in logs
assert "spawned uWSGI worker 1" in logs
assert "spawned uWSGI worker 2" in logs
assert "spawned uWSGI worker 3" not in logs
assert 'running "unix_signal:15 gracefully_kill_them_all" (master-start)' in logs
assert "success: nginx entered RUNNING state, process has stayed up for" in logs
assert "success: uwsgi entered RUNNING state, process has stayed up for" in logs
def test_defaults() -> None:
name = os.getenv("NAME")
image = f"tiangolo/uwsgi-nginx:{name}"
response_text = get_response_text1()
sleep_time = int(os.getenv("SLEEP_TIME", 3))
remove_previous_container(client)
container = client.containers.run(
image, name=CONTAINER_NAME, ports={"80": "8000"}, detach=True
)
time.sleep(sleep_time)
verify_container(container, response_text)
container.stop()
# Test that everything works after restarting too
container.start()
time.sleep(sleep_time)
verify_container(container, response_text)
container.stop()
container.remove()

View File

@ -1,90 +0,0 @@
import os
import time
import docker
import requests
from docker.models.containers import Container
from ..utils import (
CONTAINER_NAME,
get_logs,
get_nginx_config,
get_response_text1,
remove_previous_container,
)
client = docker.from_env()
def verify_container(container: Container, response_text: str) -> None:
response = requests.get("http://127.0.0.1:8000")
assert response.text == response_text
nginx_config = get_nginx_config(container)
assert "client_max_body_size 1m;" in nginx_config
assert "worker_processes 2;" in nginx_config
assert "listen 80;" in nginx_config
assert "worker_connections 2048;" in nginx_config
assert "worker_rlimit_nofile 2048;" in nginx_config
assert "daemon off;" in nginx_config
assert "listen 80;" in nginx_config
assert "include uwsgi_params;" in nginx_config
assert "uwsgi_pass unix:///tmp/uwsgi.sock;" in nginx_config
logs = get_logs(container)
assert "getting INI configuration from /app/uwsgi.ini" in logs
assert "getting INI configuration from /etc/uwsgi/uwsgi.ini" in logs
assert "ini = /app/uwsgi.ini" in logs
assert "ini = /etc/uwsgi/uwsgi.ini" in logs
assert "socket = /tmp/uwsgi.sock" in logs
assert "chown-socket = nginx:nginx" in logs
assert "chmod-socket = 664" in logs
assert "hook-master-start = unix_signal:15 gracefully_kill_them_all" in logs
assert "need-app = true" in logs
assert "die-on-term = true" in logs
assert "show-config = true" in logs
assert "wsgi-file = /app/main.py" in logs
assert "processes = 8" in logs
assert "cheaper = 3" in logs
assert "Checking for script in /app/prestart.sh" in logs
assert "Running script /app/prestart.sh" in logs
assert (
"Running inside /app/prestart.sh, you could add migrations to this file" in logs
)
assert "spawned uWSGI master process" in logs
assert "spawned uWSGI worker 1" in logs
assert "spawned uWSGI worker 2" in logs
assert "spawned uWSGI worker 3" in logs
assert "spawned uWSGI worker 4" not in logs
assert 'running "unix_signal:15 gracefully_kill_them_all" (master-start)' in logs
assert "success: nginx entered RUNNING state, process has stayed up for" in logs
assert "success: uwsgi entered RUNNING state, process has stayed up for" in logs
def test_env_vars_1() -> None:
name = os.getenv("NAME")
image = f"tiangolo/uwsgi-nginx:{name}"
response_text = get_response_text1()
sleep_time = int(os.getenv("SLEEP_TIME", 3))
remove_previous_container(client)
container = client.containers.run(
image,
name=CONTAINER_NAME,
environment={
"UWSGI_CHEAPER": 3,
"UWSGI_PROCESSES": 8,
"NGINX_MAX_UPLOAD": "1m",
"NGINX_WORKER_PROCESSES": 2,
"NGINX_WORKER_CONNECTIONS": 2048,
"NGINX_WORKER_OPEN_FILES": 2048,
},
ports={"80": "8000"},
detach=True,
)
time.sleep(sleep_time)
verify_container(container, response_text)
container.stop()
# Test that everything works after restarting too
container.start()
time.sleep(sleep_time)
verify_container(container, response_text)
container.stop()
container.remove()

View File

@ -1,14 +0,0 @@
import sys
from flask import Flask
application = Flask(__name__)
@application.route("/")
def hello():
version = "{}.{}".format(sys.version_info.major, sys.version_info.minor)
message = "Hello World from Nginx uWSGI Python {} app in a Docker container".format(
version
)
return message

View File

@ -1,10 +0,0 @@
import sys
def application(env, start_response):
version = "{}.{}".format(sys.version_info.major, sys.version_info.minor)
start_response("200 OK", [("Content-Type", "text/plain")])
message = "Hello World from Nginx uWSGI Python {} app in a Docker container".format(
version
)
return [message.encode("utf-8")]

View File

@ -1,2 +0,0 @@
[uwsgi]
wsgi-file=/application/custom_app/main.py

View File

@ -1,2 +0,0 @@
#! /usr/bin/env bash
echo "custom prestart.sh running"

View File

@ -1,10 +0,0 @@
import sys
def application(env, start_response):
version = "{}.{}".format(sys.version_info.major, sys.version_info.minor)
start_response("200 OK", [("Content-Type", "text/plain")])
message = "Hello World from Nginx uWSGI Python {} app in a Docker container".format(
version
)
return [message.encode("utf-8")]

View File

@ -1,25 +0,0 @@
user nginx;
worker_processes 2;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 2048;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
keepalive_timeout 300;
server {
listen 8080;
location / {
include uwsgi_params;
uwsgi_pass unix:///tmp/uwsgi.sock;
}
}
}
daemon off;

View File

@ -1,10 +0,0 @@
import sys
def application(env, start_response):
version = "{}.{}".format(sys.version_info.major, sys.version_info.minor)
start_response("200 OK", [("Content-Type", "text/plain")])
message = "Hello World from Nginx uWSGI Python {} app in a Docker container".format(
version
)
return [message.encode("utf-8")]

View File

@ -1,91 +0,0 @@
import os
import time
from pathlib import Path
import docker
import requests
from docker.models.containers import Container
from ..utils import (
CONTAINER_NAME,
generate_dockerfile_content_custom_app,
get_logs,
get_nginx_config,
get_response_text2,
remove_previous_container,
)
client = docker.from_env()
def verify_container(container: Container, response_text: str) -> None:
response = requests.get("http://127.0.0.1:8000")
assert response.text == response_text
nginx_config = get_nginx_config(container)
assert "client_max_body_size 0;" in nginx_config
assert "worker_processes 1;" in nginx_config
assert "listen 8080;" in nginx_config
assert "worker_connections 1024;" in nginx_config
assert "worker_rlimit_nofile;" not in nginx_config
assert "daemon off;" in nginx_config
assert "include uwsgi_params;" in nginx_config
assert "uwsgi_pass unix:///tmp/uwsgi.sock;" in nginx_config
logs = get_logs(container)
assert "getting INI configuration from /application/custom_app/uwsgi.ini" in logs
assert "getting INI configuration from /etc/uwsgi/uwsgi.ini" in logs
assert "ini = /application/custom_app/uwsgi.ini" in logs
assert "ini = /etc/uwsgi/uwsgi.ini" in logs
assert "socket = /tmp/uwsgi.sock" in logs
assert "chown-socket = nginx:nginx" in logs
assert "chmod-socket = 664" in logs
assert "hook-master-start = unix_signal:15 gracefully_kill_them_all" in logs
assert "need-app = true" in logs
assert "die-on-term = true" in logs
assert "show-config = true" in logs
assert "wsgi-file = /application/custom_app/main.py" in logs
assert "processes = 16" in logs
assert "cheaper = 2" in logs
assert "Checking for script in /app/prestart.sh" in logs
assert "Running script /app/prestart.sh" in logs
assert "custom prestart.sh running" in logs
assert "spawned uWSGI master process" in logs
assert "spawned uWSGI worker 1" in logs
assert "spawned uWSGI worker 2" in logs
assert "spawned uWSGI worker 3" not in logs
assert 'running "unix_signal:15 gracefully_kill_them_all" (master-start)' in logs
assert "success: nginx entered RUNNING state, process has stayed up for" in logs
assert "success: uwsgi entered RUNNING state, process has stayed up for" in logs
def test_env_vars_1() -> None:
name = os.getenv("NAME", "")
dockerfile_content = generate_dockerfile_content_custom_app(name)
dockerfile = "Dockerfile"
response_text = get_response_text2()
sleep_time = int(os.getenv("SLEEP_TIME", 3))
remove_previous_container(client)
tag = "uwsgi-nginx-testimage"
test_path = Path(__file__)
path = test_path.parent / "custom_app"
dockerfile_path = path / dockerfile
dockerfile_path.write_text(dockerfile_content)
client.images.build(path=str(path), dockerfile=dockerfile, tag=tag)
container = client.containers.run(
tag,
name=CONTAINER_NAME,
environment={
"UWSGI_INI": "/application/custom_app/uwsgi.ini",
"LISTEN_PORT": "8080",
},
ports={"8080": "8000"},
detach=True,
)
time.sleep(sleep_time)
verify_container(container, response_text)
container.stop()
# Test that everything works after restarting too
container.start()
time.sleep(sleep_time)
verify_container(container, response_text)
container.stop()
container.remove()

View File

@ -1,85 +0,0 @@
import os
import time
from pathlib import Path
import docker
import requests
from docker.models.containers import Container
from ..utils import (
CONTAINER_NAME, generate_dockerfile_content_app_with_installs,
get_logs,
get_nginx_config,
get_response_text2,
remove_previous_container,
)
client = docker.from_env()
def verify_container(container: Container, response_text: str) -> None:
response = requests.get("http://127.0.0.1:8000")
assert response.text == response_text
nginx_config = get_nginx_config(container)
assert "client_max_body_size 0;" in nginx_config
assert "worker_processes 1;" in nginx_config
assert "listen 80;" in nginx_config
assert "worker_connections 1024;" in nginx_config
assert "worker_rlimit_nofile;" not in nginx_config
assert "daemon off;" in nginx_config
assert "include uwsgi_params;" in nginx_config
assert "uwsgi_pass unix:///tmp/uwsgi.sock;" in nginx_config
logs = get_logs(container)
assert "getting INI configuration from /app/uwsgi.ini" in logs
assert "getting INI configuration from /etc/uwsgi/uwsgi.ini" in logs
assert "ini = /app/uwsgi.ini" in logs
assert "ini = /etc/uwsgi/uwsgi.ini" in logs
assert "socket = /tmp/uwsgi.sock" in logs
assert "chown-socket = nginx:nginx" in logs
assert "chmod-socket = 664" in logs
assert "hook-master-start = unix_signal:15 gracefully_kill_them_all" in logs
assert "need-app = true" in logs
assert "die-on-term = true" in logs
assert "show-config = true" in logs
assert "wsgi-file = /app/main.py" in logs
assert "processes = 16" in logs
assert "cheaper = 2" in logs
assert "Checking for script in /app/prestart.sh" in logs
assert "Running script /app/prestart.sh" in logs
assert (
"Running inside /app/prestart.sh, you could add migrations to this file" in logs
)
assert "spawned uWSGI master process" in logs
assert "spawned uWSGI worker 1" in logs
assert "spawned uWSGI worker 2" in logs
assert "spawned uWSGI worker 3" not in logs
assert 'running "unix_signal:15 gracefully_kill_them_all" (master-start)' in logs
assert "success: nginx entered RUNNING state, process has stayed up for" in logs
assert "success: uwsgi entered RUNNING state, process has stayed up for" in logs
def test_env_vars_1() -> None:
name = os.getenv("NAME", "")
dockerfile_content = generate_dockerfile_content_app_with_installs(name)
dockerfile = "Dockerfile"
response_text = get_response_text2()
sleep_time = int(os.getenv("SLEEP_TIME", 3))
remove_previous_container(client)
tag = "uwsgi-nginx-testimage"
test_path = Path(__file__)
path = test_path.parent / "app_with_installs"
dockerfile_path = path / dockerfile
dockerfile_path.write_text(dockerfile_content)
client.images.build(path=str(path), dockerfile=dockerfile, tag=tag)
container = client.containers.run(
tag, name=CONTAINER_NAME, ports={"80": "8000"}, detach=True
)
time.sleep(sleep_time)
verify_container(container, response_text)
container.stop()
# Test that everything works after restarting too
container.start()
time.sleep(sleep_time)
verify_container(container, response_text)
container.stop()
container.remove()

View File

@ -1,87 +0,0 @@
import os
import time
from pathlib import Path
import docker
import requests
from docker.models.containers import Container
from ..utils import (
CONTAINER_NAME,
generate_dockerfile_content_custom_nginx_app,
get_logs,
get_nginx_config,
get_response_text2,
remove_previous_container,
)
client = docker.from_env()
def verify_container(container: Container, response_text: str) -> None:
response = requests.get("http://127.0.0.1:8080")
assert response.text == response_text
nginx_config = get_nginx_config(container)
assert "client_max_body_size 0;" not in nginx_config
assert "worker_processes 2;" in nginx_config
assert "listen 8080;" in nginx_config
assert "worker_connections 2048;" in nginx_config
assert "worker_rlimit_nofile;" not in nginx_config
assert "daemon off;" in nginx_config
assert "include uwsgi_params;" in nginx_config
assert "uwsgi_pass unix:///tmp/uwsgi.sock;" in nginx_config
assert "keepalive_timeout 300;" in nginx_config
logs = get_logs(container)
assert "getting INI configuration from /app/uwsgi.ini" in logs
assert "getting INI configuration from /etc/uwsgi/uwsgi.ini" in logs
assert "ini = /app/uwsgi.ini" in logs
assert "ini = /etc/uwsgi/uwsgi.ini" in logs
assert "socket = /tmp/uwsgi.sock" in logs
assert "chown-socket = nginx:nginx" in logs
assert "chmod-socket = 664" in logs
assert "hook-master-start = unix_signal:15 gracefully_kill_them_all" in logs
assert "need-app = true" in logs
assert "die-on-term = true" in logs
assert "show-config = true" in logs
assert "wsgi-file = /app/main.py" in logs
assert "processes = 16" in logs
assert "cheaper = 2" in logs
assert "Checking for script in /app/prestart.sh" in logs
assert "Running script /app/prestart.sh" in logs
assert (
"Running inside /app/prestart.sh, you could add migrations to this file" in logs
)
assert "spawned uWSGI master process" in logs
assert "spawned uWSGI worker 1" in logs
assert "spawned uWSGI worker 2" in logs
assert "spawned uWSGI worker 3" not in logs
assert 'running "unix_signal:15 gracefully_kill_them_all" (master-start)' in logs
assert "success: nginx entered RUNNING state, process has stayed up for" in logs
assert "success: uwsgi entered RUNNING state, process has stayed up for" in logs
def test_env_vars_1() -> None:
name = os.getenv("NAME", "")
dockerfile_content = generate_dockerfile_content_custom_nginx_app(name)
dockerfile = "Dockerfile"
response_text = get_response_text2()
sleep_time = int(os.getenv("SLEEP_TIME", 3))
remove_previous_container(client)
tag = "uwsgi-nginx-testimage"
test_path = Path(__file__)
path = test_path.parent / "custom_nginx_app"
dockerfile_path = path / dockerfile
dockerfile_path.write_text(dockerfile_content)
client.images.build(path=str(path), dockerfile=dockerfile, tag=tag)
container = client.containers.run(
tag, name=CONTAINER_NAME, ports={"8080": "8080"}, detach=True
)
time.sleep(sleep_time)
verify_container(container, response_text)
container.stop()
# Test that everything works after restarting too
container.start()
time.sleep(sleep_time)
verify_container(container, response_text)
container.stop()
container.remove()

View File

@ -1,86 +0,0 @@
import os
import time
from pathlib import Path
import docker
import requests
from docker.models.containers import Container
from ..utils import (
CONTAINER_NAME,
generate_dockerfile_content_simple_app,
get_logs,
get_nginx_config,
get_response_text2,
remove_previous_container,
)
client = docker.from_env()
def verify_container(container: Container, response_text: str) -> None:
response = requests.get("http://127.0.0.1:8000")
assert response.text == response_text
nginx_config = get_nginx_config(container)
assert "client_max_body_size 0;" in nginx_config
assert "worker_processes 1;" in nginx_config
assert "listen 80;" in nginx_config
assert "worker_connections 1024;" in nginx_config
assert "worker_rlimit_nofile;" not in nginx_config
assert "daemon off;" in nginx_config
assert "include uwsgi_params;" in nginx_config
assert "uwsgi_pass unix:///tmp/uwsgi.sock;" in nginx_config
logs = get_logs(container)
assert "getting INI configuration from /app/uwsgi.ini" in logs
assert "getting INI configuration from /etc/uwsgi/uwsgi.ini" in logs
assert "ini = /app/uwsgi.ini" in logs
assert "ini = /etc/uwsgi/uwsgi.ini" in logs
assert "socket = /tmp/uwsgi.sock" in logs
assert "chown-socket = nginx:nginx" in logs
assert "chmod-socket = 664" in logs
assert "hook-master-start = unix_signal:15 gracefully_kill_them_all" in logs
assert "need-app = true" in logs
assert "die-on-term = true" in logs
assert "show-config = true" in logs
assert "wsgi-file = /app/main.py" in logs
assert "processes = 16" in logs
assert "cheaper = 2" in logs
assert "Checking for script in /app/prestart.sh" in logs
assert "Running script /app/prestart.sh" in logs
assert (
"Running inside /app/prestart.sh, you could add migrations to this file" in logs
)
assert "spawned uWSGI master process" in logs
assert "spawned uWSGI worker 1" in logs
assert "spawned uWSGI worker 2" in logs
assert "spawned uWSGI worker 3" not in logs
assert 'running "unix_signal:15 gracefully_kill_them_all" (master-start)' in logs
assert "success: nginx entered RUNNING state, process has stayed up for" in logs
assert "success: uwsgi entered RUNNING state, process has stayed up for" in logs
def test_env_vars_1() -> None:
name = os.getenv("NAME", "")
dockerfile_content = generate_dockerfile_content_simple_app(name)
dockerfile = "Dockerfile"
response_text = get_response_text2()
sleep_time = int(os.getenv("SLEEP_TIME", 3))
remove_previous_container(client)
tag = "uwsgi-nginx-testimage"
test_path = Path(__file__)
path = test_path.parent / "simple_app"
dockerfile_path = path / dockerfile
dockerfile_path.write_text(dockerfile_content)
client.images.build(path=str(path), dockerfile=dockerfile, tag=tag)
container = client.containers.run(
tag, name=CONTAINER_NAME, ports={"80": "8000"}, detach=True
)
time.sleep(sleep_time)
verify_container(container, response_text)
container.stop()
# Test that everything works after restarting too
container.start()
time.sleep(sleep_time)
verify_container(container, response_text)
container.stop()
container.remove()

View File

@ -1,63 +0,0 @@
import os
from docker.client import DockerClient
from docker.errors import NotFound
from docker.models.containers import Container
CONTAINER_NAME = "uwsgi-nginx-test"
def get_logs(container: Container) -> str:
logs = container.logs()
return logs.decode("utf-8")
def get_nginx_config(container: Container) -> str:
result = container.exec_run(f"/usr/sbin/nginx -T")
return result.output.decode()
def remove_previous_container(client: DockerClient) -> None:
try:
previous = client.containers.get(CONTAINER_NAME)
previous.stop()
previous.remove()
except NotFound:
return None
def get_response_text1() -> str:
python_version = os.getenv("PYTHON_VERSION")
return f"Hello World from a default Nginx uWSGI Python {python_version} app in a Docker container (default)"
def get_response_text2() -> str:
python_version = os.getenv("PYTHON_VERSION")
return f"Hello World from Nginx uWSGI Python {python_version} app in a Docker container"
def generate_dockerfile_content_custom_app(name: str) -> str:
content = f"FROM tiangolo/uwsgi-nginx:{name}\n"
content += "COPY ./application /application\n"
content += "COPY ./prestart.sh /app/prestart.sh\n"
content += "WORKDIR /application\n"
return content
def generate_dockerfile_content_custom_nginx_app(name: str) -> str:
content = f"FROM tiangolo/uwsgi-nginx:{name}\n"
content += "COPY app /app\n"
return content
def generate_dockerfile_content_simple_app(name: str) -> str:
content = f"FROM tiangolo/uwsgi-nginx:{name}\n"
content += "COPY ./app/main.py /app/main.py\n"
return content
def generate_dockerfile_content_app_with_installs(name: str) -> str:
content = f"FROM tiangolo/uwsgi-nginx:{name}\n"
content += "RUN pip install flask\n"
content += "COPY ./app/main.py /app/main.py\n"
return content