Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,11 @@ nextjs/**/node_modules/
# Angular
angular/**/.angular

# End of https://www.toptal.com/developers/gitignore/api/macos

## ------- Python -------
venv/
__pycache__/
*.py[cod]
*$py.class

# End of https://www.toptal.com/developers/gitignore/api/macos
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ Docker Implementation
* ExpressJS
* Django
* Flask
* Fastapi
* [Fastapi](https://github.com/agung-learns/docker-implementation/tree/main/fastapi/fastapi-docker)

### Contributors
<table>
Expand Down
37 changes: 37 additions & 0 deletions fastapi/fastapi-docker/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
Fastapi with Docker
================================


## How to Run

### Local
```shell
docker compose up \
-f docker-compose.local.yaml --build -d

fastapi dev cmd/cmd.py
```

### Production

#### Docker
```shell
docker compose up -d --build
```

#### Kubernetes
```shell
kubectl apply -f deploy/k8s
```

## Contributors
<table>
<tr>
<td align="center">
<a href="https://www.linkedin.com/in/agung96tm/">
<img src="https://avatars.githubusercontent.com/u/1901484?v=4" width="100px;" alt=""/><br />
<b>Agung Yuliyanto</b><br>
</a>
</td>
</tr>
</table>
117 changes: 117 additions & 0 deletions fastapi/fastapi-docker/alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
# A generic, single database configuration.

[alembic]
# path to migration scripts
# Use forward slashes (/) also on windows to provide an os agnostic path
script_location = migrations

# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s

# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .

# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python>=3.9 or backports.zoneinfo library.
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
# string value is passed to ZoneInfo()
# leave blank for localtime
# timezone =

# max length of characters to apply to the "slug" field
# truncate_slug_length = 40

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false

# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false

# version location specification; This defaults
# to migrations/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "version_path_separator" below.
# version_locations = %(here)s/bar:%(here)s/bat:migrations/versions

# version path separator; As mentioned above, this is the character used to split
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
# Valid values for version_path_separator are:
#
# version_path_separator = :
# version_path_separator = ;
# version_path_separator = space
# version_path_separator = newline
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.

# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false

# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8

sqlalchemy.url = driver://user:pass@localhost/dbname


[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples

# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME

# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
# hooks = ruff
# ruff.type = exec
# ruff.executable = %(here)s/.venv/bin/ruff
# ruff.options = --fix REVISION_SCRIPT_FILENAME

# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
13 changes: 13 additions & 0 deletions fastapi/fastapi-docker/api/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from fastapi import FastAPI


def create_app() -> FastAPI:
app = FastAPI()
register_routers(app)
return app


def register_routers(app: FastAPI) -> None:
from api.apps import user_router

app.include_router(user_router)
1 change: 1 addition & 0 deletions fastapi/fastapi-docker/api/apps/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .user import user_router
5 changes: 5 additions & 0 deletions fastapi/fastapi-docker/api/apps/user/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from fastapi import APIRouter

user_router = APIRouter(tags=["user"])

from . import views, models # noqa
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
41 changes: 41 additions & 0 deletions fastapi/fastapi-docker/cmd/cmd.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import subprocess

import click
import uvicorn
from api.app import create_app

app = create_app()


@click.group()
def cli():
pass


@cli.command()
@click.option("--host", default="localhost", help="Host to bind the server to.")
@click.option("--port", default=8000, help="Port to bind the server to.")
@click.option("--prod", default=False, help="Run in production mode.")
def runserver(host: str, port: int, prod: bool) -> None:
click.echo(f"Starting server on {host}:{port}")
uvicorn.run(app, host=host, port=port)


@cli.group()
def migrations():
pass


@migrations.command()
def generate():
subprocess.run(["alembic", "revision", "--autogenerate"])


@migrations.command()
def up():
subprocess.run(["alembic", "upgrade", "head"])


@migrations.command()
def down():
subprocess.run(["alembic", "downgrade", "-1"])
Empty file.
78 changes: 78 additions & 0 deletions fastapi/fastapi-docker/deploy/docker/entrypoint.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
#!/bin/bash

set -o errexit
set -o pipefail
set -o nounset

postgres_ready() {
python << END
import sys

import psycopg
import urllib.parse as urlparse
import os

url = urlparse.urlparse(os.environ['DATABASE_URL'])
dbname = url.path[1:]
user = url.username
password = url.password
host = url.hostname
port = url.port

try:
psycopg.connect(
dbname=dbname,
user=user,
password=password,
host=host,
port=port
)
except psycopg.OperationalError:
sys.exit(-1)
sys.exit(0)

END
}
until postgres_ready; do
>&2 echo 'Waiting for PostgreSQL to become available...'
sleep 1
done
>&2 echo 'PostgreSQL is available'


vector_ready() {
python << END
import sys

import psycopg
import urllib.parse as urlparse
import os

url = urlparse.urlparse(os.environ['VECTOR_URL'])
dbname = url.path[1:]
user = url.username
password = url.password
host = url.hostname
port = url.port

try:
psycopg.connect(
dbname=dbname,
user=user,
password=password,
host=host,
port=port
)
except psycopg.OperationalError:
sys.exit(-1)
sys.exit(0)

END
}
until vector_ready; do
>&2 echo 'Waiting for Vector to become available...'
sleep 1
done
>&2 echo 'Vector is available'

exec "$@"
4 changes: 4 additions & 0 deletions fastapi/fastapi-docker/deploy/docker/nginx/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
FROM nginx:1.25.3-alpine

RUN rm /etc/nginx/conf.d/default.conf
COPY nginx.conf /etc/nginx/conf.d
16 changes: 16 additions & 0 deletions fastapi/fastapi-docker/deploy/docker/nginx/nginx.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
upstream api-server {
server api:8000;
}

server {
listen 80;
location / {
proxy_pass http://api-server;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_redirect off;
}
location /upload/ {
alias /app/upload/;
}
}
8 changes: 8 additions & 0 deletions fastapi/fastapi-docker/deploy/docker/start.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#!/bin/bash

set -o errexit
set -o pipefail
set -o nounset

alembic upgrade head
uvicorn cmd.cmd:app --reload --reload-dir api --host 0.0.0.0 --port 8000
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
8 changes: 8 additions & 0 deletions fastapi/fastapi-docker/deploy/k8s/k8s-env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
apiVersion: v1
kind: Secret
metadata:
name: gap-ai-env
namespace: prod
type: Opaque
data:
DATABASE_URL:
Empty file.
17 changes: 17 additions & 0 deletions fastapi/fastapi-docker/docker-compose.local.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
version: '3'

services:
db:
container_name: "fastapi-local-db"
image: "postgres:16.2-alpine"
environment:
- POSTGRES_USER=gapai_user
- POSTGRES_PASSWORD=gapai_password
- POSTGRES_DB=gapai_db
volumes:
- api_local_db:/var/libs/postgresql/data/
ports:
- "5432:5432"

volumes:
api_local_db: {}
Loading