Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
railway-bot committed Jul 1, 2024
0 parents commit 7eaf2f4
Show file tree
Hide file tree
Showing 21 changed files with 774 additions and 0 deletions.
11 changes: 11 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates

version: 2
updates:
- package-ecosystem: "pip" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "weekly"
48 changes: 48 additions & 0 deletions .github/workflows/build-container.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
name: "Build Django image"

concurrency:
group: ${{ github.ref }}
cancel-in-progress: true

on:
push:
branches:
- "main"
pull_request:
branches:
- "main"
workflow_dispatch:

permissions:
contents: read
packages: write

jobs:
build-push:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3

- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2

- name: Login to GitHub Container Registry
uses: docker/login-action@v2
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ github.token }}

- name: Set REGISTRY env variable
run: echo "REGISTRY=ghcr.io/$(echo ${{ github.repository }} | tr '[:upper:]' '[:lower:]')" >> $GITHUB_ENV

- name: Build container image
uses: docker/build-push-action@v4
id: build-image
with:
context: ./.
file: ./Dockerfile
push: ${{ github.event_name != 'pull_request' }}
tags: ${{env.REGISTRY}}:${{github.run_number}}, ${{env.REGISTRY}}:latest
cache-from: type=gha
cache-to: type=gha,mode=max
177 changes: 177 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# 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/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
test_emails/
test_backups/

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
# Ignore 'real' .env files, but ensure that .erb ending env files are committed as these are templates
.env
.env.*
!.env*.erb
*.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

.DS_Store

# Django
*.sql

# Linters
**.ruff_cache

# Profilers
importtime.txt
51 changes: 51 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
ARG PYTHON_BUILD_VERSION=3.11

FROM python:$PYTHON_BUILD_VERSION-slim AS BASE
WORKDIR /app

ENV PIP_DEFAULT_TIMEOUT=100 \
# Allow statements and log messages to immediately appear
PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
# disable a pip version check to reduce run-time & log-spam
PIP_DISABLE_PIP_VERSION_CHECK=1 \
# cache is useless in docker image, so disable it to reduce image size
PIP_NO_CACHE_DIR=1

# Update and install dependencies
RUN apt-get update && \
apt-get -y upgrade && \
apt-get -y install --no-install-recommends python3-dev gcc libc-dev vim curl postgresql-client && \
# Clean up
apt-get autoremove -y && \
apt-get clean && \
rm -rf /var/lib/apt/lists/* && \
# Add a non-root user
groupadd -g 999 python && \
useradd -r -u 999 -g python python

WORKDIR /app

# Python Dependencies
COPY --chown=python:python ./requirements.txt /app/
RUN pip install --upgrade pip \
&& pip install -r requirements.txt --no-cache-dir --compile

# Clean up
RUN apt-get -y purge gcc libc-dev python3-dev

# Add all application code from this folder, including deployment entrypoints
COPY --chown=python:python ./ /app

# Create staticfiles folder
RUN mkdir -p staticfiles && \
chown -R python:python staticfiles

# Make entrypoints executable
RUN chmod +x /app/deployment/server-entrypoint.sh && \
chmod +x /app/deployment/worker-entrypoint.sh

USER 999

EXPOSE 8000
CMD [ "/app/deployment/server-entrypoint.sh" ]
87 changes: 87 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# `railway_django_stack`

[![Deploy on Railway](https://railway.app/button.svg)](https://railway.app/template/NBR_V3?referralCode=6rOei9)

Full Django/Postgres stack with Celery tasks and Redis as cache/queue.

## Overview

Deploy a "complete" Django setup - DB, caching and background tasks with Celery are all set up and ready to go.

Check out the full readme and brief on GitHub: https://github.com/Antvirf/railway_django_stack

## Deploying the template

1. In the deployment screen, you will need to configure a `DJANGO_SECRET_KEY`. You can use the below snippet to do that or otherwise generate your own.
<details>
<summary>Snippet to create secret</summary>

**This assumes your default python installation has Django installed.**

```bash
python -c 'from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())'
```

</details>
1. Once the containers have been deployed, please take the following steps to delete public proxy addresses, as you will not need to access the private services directly:
- Go to the **Postgres** service > Settings > Networking, delete the proxy
- Go to the **Redis** service > Settings > Networking, delete the proxy

## Resources

This template deploys:

- 1 service running Django
- 1 service running Celery (same as container #1 but with different startup command)
- 1 service running Redis
- 1 service running Postgres

You can test the setup locally with docker compose:

```bash
git clone https://github.com/Antvirf/railway_django_stack
cd railway_django_stack
docker-compose up
```

## Service diagram

> **Warning**
> Please check the instructions above on deploying the template. By default, Railway creates publicly available proxies for your Postgres and Redis services - make sure to delete them. Should you ever need direct access, creating the proxies is just a few clicks.

```mermaid
flowchart LR
subgraph rwp["Your Railway Project"]
subgraph public["Publicly exposed services"]
django["App container\n(Django server)"]
end
subgraph private["Private services"]
celery["App container\n(Celery worker)"]
psql["PostgreSQL"]
redis["Redis"]
end
end
users["Users"] --> django
django --> celery
django --> psql
celery --> psql
celery --> redis
django --> redis
```

## Django project setup

This is a barebones Django-project with the following additions/updates:

- Configures a PostgreSQL database
- Configures a Redis cache
- Configures Celery, and installs the following add-on apps:
- [`django-celery-beat`](https://github.com/celery/django-celery-beat) for periodic task management
- [`django-celery-results`](https://github.com/celery/django-celery-results) for viewing results of Celery tasks in Django Admin
- Uses [`python-decouple`](https://github.com/HBNetwork/python-decouple) to manage settings via environment varialbes
- Uses [`whitenoise`](https://github.com/evansd/whitenoise) to make serving static assets easy
- Installs and runs with [`gunicorn`](https://github.com/benoitc/gunicorn)
12 changes: 12 additions & 0 deletions deployment/gunicorn_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Gunicorn configuration file
# https://docs.gunicorn.org/en/stable/configure.html#configuration-file
# https://docs.gunicorn.org/en/stable/settings.html


workers = 3
max_requests = 1000
max_requests_jitter = 50

log_file = "-"
accesslog = "-"
access_log_format = '[gunicorn-access-log] "%(r)s" %(s)s %(b)s'
Loading

0 comments on commit 7eaf2f4

Please sign in to comment.