This commit is contained in:
Waylon S. Walker 2024-10-29 20:14:57 -05:00
parent 986b8ba632
commit 2e03f31a09
3 changed files with 296 additions and 31 deletions

View file

@ -1,30 +1,136 @@
from python:3.13 FROM ubuntu:noble AS build
# The following does not work in Podman unless you build in Docker
# compatibility mode: <https://github.com/containers/podman/issues/8477>
# You can manually prepend every RUN script with `set -ex` too.
# SHELL ["sh", "-exc"]
### Start build prep.
### This should be a separate build container for better reuse.
RUN <<EOT
apt-get update -qy
apt-get install -qyy \
-o APT::Install-Recommends=false \
-o APT::Install-Suggests=false \
build-essential \
ca-certificates \
python3-setuptools \
python3.12-dev
EOT
# Security-conscious organizations should package/review uv themselves.
COPY --from=ghcr.io/astral-sh/uv:latest /uv /usr/local/bin/uv
# - Silence uv complaining about not being able to use hard links,
# - tell uv to byte-compile packages for faster application startups,
# - prevent uv from accidentally downloading isolated Python builds,
# - pick a Python,
# - and finally declare `/app` as the target for `uv sync`.
ENV UV_LINK_MODE=copy \
UV_COMPILE_BYTECODE=1 \
UV_PYTHON_DOWNLOADS=never \
UV_PYTHON=python3.12 \
UV_PROJECT_ENVIRONMENT=/app
### End build prep -- this is where your app Dockerfile should start.
# Since there's no point in shipping lock files, we move them
# into a directory that is NOT copied into the runtime image.
# The trailing slash makes COPY create `/_lock/` automagically.
COPY pyproject.toml /_lock/
COPY uv.lock /_lock/
# Synchronize DEPENDENCIES without the application itself.
# This layer is cached until uv.lock or pyproject.toml change.
# You can create `/app` using `uv venv` in a separate `RUN`
# step to have it cached, but with uv it's so fast, it's not worth
# it, so we let `uv sync` create it for us automagically.
RUN --mount=type=cache,target=/root/.cache <<EOT
cd /_lock
mkdir -p src/fastapi_dynamic_response
echo '__version__ = "0.0.0"' > src/fastapi_dynamic_response/__about__.py
touch README.md
uv sync \
--locked \
--no-dev \
--no-install-project
EOT
# Now install the APPLICATION from `/src` without any dependencies.
# `/src` will NOT be copied into the runtime container.
# LEAVE THIS OUT if your application is NOT a proper Python package.
# As of uv 0.4.11, you can also use
# `cd /src && uv sync --locked --no-dev --no-editable` instead.
COPY . /src
RUN --mount=type=cache,target=/root/.cache \
uv pip install \
--python=$UV_PROJECT_ENVIRONMENT \
--no-deps \
/src
##########################################################################
FROM ubuntu:noble
# SHELL ["sh", "-exc"]
# Optional: add the application virtualenv to search path.
ENV PATH=/app/bin:$PATH
# Don't run your app as root.
RUN <<EOT
groupadd -r app
useradd -r -d /app -g app -N app
EOT
ENTRYPOINT ["/docker-entrypoint.sh"]
# See <https://hynek.me/articles/docker-signals/>.
STOPSIGNAL SIGINT
# Note how the runtime dependencies differ from build-time ones.
# Notably, there is no uv either!
RUN <<EOT
apt-get update -qy
apt-get install -qyy \
-o APT::Install-Recommends=false \
-o APT::Install-Suggests=false \
python3.12 \
libpython3.12 \
libpcre3 \
libxml2
apt-get clean
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
EOT
COPY docker-entrypoint.sh /
# Copy the pre-built `/app` directory to the runtime container
# and change the ownership to user app and group app in one step.
COPY --from=build --chown=app:app /app /app
# If your application is NOT a proper Python package that got
# pip-installed above, you need to copy your application into
# the container HERE:
# COPY . /app/whereever-your-entrypoint-finds-it
USER app
WORKDIR /app WORKDIR /app
COPY src src
COPY pyproject.toml .
COPY uv.lock .
COPY README.md .
COPY requirements.txt .
ENV VIRTUAL_ENV=/app/.venv # Strictly optional, but I like it for introspection of what I've built
ENV PATH=${VIRTUAL_ENV}/bin:${PATH} # and run a smoke test that the application can, in fact, be imported.
RUN <<EOT
RUN useradd -m appuser && chown -R appuser:appuser /app set -e
USER appuser python -V
python -Im site
ENV HOME=/home/appuser python -Ic 'import fastapi_dynamic_response'
ENV PATH=${HOME}/.local/bin:${PATH} EOT
RUN pip install --upgrade pip && \
pip install uv && \
uv venv
RUN uv pip install -r requirements.txt
RUN uv pip install .
COPY static static COPY static static
COPY templates templates COPY templates templates
EXPOSE 8000 EXPOSE 8000
ENTRYPOINT ["uvicorn"] ENTRYPOINT ["fdr_app"]
CMD ["src.fastapi_dynamic_response.main:app", "--host", "0.0.0.0", "--port", "8000"] CMD ["app", "run", ]

View file

@ -3,12 +3,16 @@ set dotenv-load
default: default:
@just --choose @just --choose
setup: kind-create argo-install setup: kind-create
teardown: kind-delete teardown: kind-delete
version:
echo ${VERSION}
kind-create: kind-create:
kind create cluster --name fastapi-dynamic-response kind create cluster --name fastapi-dynamic-response --config kind-config.yaml
kind load docker-image --name fastapi-dynamic-response docker.io/waylonwalker/fastapi-dynamic-response:${VERSION}
kind-delete: kind-delete:
kind delete cluster --name fastapi-dynamic-response kind delete cluster --name fastapi-dynamic-response
@ -24,16 +28,26 @@ compile:
venv: venv:
uv venv uv venv
build-podman: build-podman:
podman build -t docker.io/waylonwalker/fastapi-dynamic-response:0.0.2 . podman build -t docker.io/waylonwalker/fastapi-dynamic-response:${VERSION} .
run-podman:
podman run -it --rm -p 8000:8000 --name fastapi-dynamic-response docker.io/waylonwalker/fastapi-dynamic-response:0.0.2
push-podman:
podman push docker.io/waylonwalker/fastapi-dynamic-response:0.0.2
run:
uv run -- uvicorn --reload --log-level debug src.fastapi_dynamic_response.main:app
run:
@just -l | grep '^\s*run-' | gum filter --header 'Choose a command' | xargs -I {} just {}
run-local:
uv run -- fdr_app app run
run-workers: run-workers:
uv run -- uvicorn --workers 6 --log-level debug src.fastapi_dynamic_response.main:app uv run -- uvicorn --workers 6 --log-level debug src.fastapi_dynamic_response.main:app
run-podman:
podman run -it --rm -p 8000:8000 --name fastapi-dynamic-response docker.io/waylonwalker/fastapi-dynamic-response:${VERSION} app run
run-podman-bash:
podman run -it --rm -p 8000:8000 --name fastapi-dynamic-response --entrypoint bash docker.io/waylonwalker/fastapi-dynamic-response:${VERSION}
local-run:
uv run -- uvicorn --workers 6 --log-level debug src.fastapi_dynamic_response.main:app
push-podman:
podman push docker.io/waylonwalker/fastapi-dynamic-response:${VERSION}
podman tag docker.io/waylonwalker/fastapi-dynamic-response:${VERSION} docker.io/waylonwalker/fastapi-dynamic-response:latest
podman push docker.io/waylonwalker/fastapi-dynamic-response:latest
get-authorized: get-authorized:
http GET :8000/example 'Authorization:Basic user1:password123' http GET :8000/example 'Authorization:Basic user1:password123'

145
k8s/base/deployment.yaml Normal file
View file

@ -0,0 +1,145 @@
apiVersion: v1
kind: Namespace
metadata:
name: fastapi-dynamic-response
namespace: fastapi-dynamic-response
---
apiVersion: v1
kind: Service
metadata:
name: fastapi-dynamic-response
namespace: fastapi-dynamic-response
spec:
ports:
- name: "8000"
port: 8000
targetPort: 8000
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: fastapi-dynamic-response
namespace: fastapi-dynamic-response
spec:
replicas: 3
selector:
matchLabels:
app: fastapi-dynamic-response
strategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 0
maxSurge: 1
template:
metadata:
labels:
app: fastapi-dynamic-response
spec:
# affinity:
# podAntiAffinity:
# requiredDuringSchedulingIgnoredDuringExecution:
# - labelSelector:
# matchLabels:
# app: fastapi-dynamic-response
# topologyKey: "kubernetes.io/hostname"
containers:
- image: docker.io/waylonwalker/fastapi-dynamic-response:0.0.2
name: fastapi-dynamic-response
args: ["./.venv/bin/uvicorn", "src.fastapi_dynamic_response.main:app", "--host", "0.0.0.0", "--port", "8000"]
ports:
- containerPort: 8000
protocol: TCP
imagePullPolicy: Always
securityContext:
readOnlyRootFilesystem: true
runAsNonRoot: true
allowPrivilegeEscalation: false
capabilities:
drop:
- ALL
runAsUser: 10001
runAsGroup: 10001
readinessProbe:
httpGet:
path: /livez
port: 8000
initialDelaySeconds: 3
periodSeconds: 10
failureThreshold: 3
livenessProbe:
httpGet:
path: /healthz
port: 8000
initialDelaySeconds: 3
periodSeconds: 15
failureThreshold: 3
resources:
requests:
cpu: 100m
memory: 100Mi
ephemeral-storage: 1Gi
limits:
cpu: 500m
memory: 500Mi
ephemeral-storage: 2Gi
restartPolicy: Always
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: fastapi-dynamic-response
namespace: fastapi-dynamic-response
spec:
rules:
- host: app.fokais.com
http:
paths:
- backend:
service:
name: fastapi-dynamic-response
port:
number: 8000
path: /
pathType: Prefix
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-fastapi-dynamic-response
namespace: fastapi-dynamic-response
spec:
podSelector:
matchLabels:
app: fastapi-dynamic-response
policyTypes:
- Ingress
- Egress
ingress:
- from:
- podSelector: {}
# - namespaceSelector:
# matchLabels:
# name: fastapi-dynamic-response
ports:
- protocol: TCP
port: 8000
egress:
- to:
- ipBlock:
cidr: 0.0.0.0/0
ports:
- protocol: TCP
port: 443
- protocol: TCP
port: 80
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: fastapi-dynamic-response-pdb
namespace: fastapi-dynamic-response
spec:
minAvailable: 1
selector:
matchLabels:
app: fastapi-dynamic-response