Deploying Your Django Apps to Google Cloud
Your VM runs one Postgres database, one reverse proxy (Caddy), and up to five Django apps — each on its own subdomain with automatic HTTPS. You develop with SQLite on your laptop and deploy with git push + one command.
For now, these instructions deploy locallibrary only. The server is already set up for kahduke and your final project; their steps will be added later.
collectstatic and deployed sites had no CSS, and chat could not reach Redis on the server. If you already worked through step 1, go back and do three things: add WhiteNoise as a dependency, add STATIC_ROOT and the WhiteNoise middleware to settings.py, and update CHANNEL_LAYERS to read REDIS_URL, as now shown in Part 2 of the Channels tutorial. If you copied the Dockerfile before this update, change its collectstatic line too. Then commit, push, and rebuild (see Deploying updates).Prerequisites
- A Google Cloud account with access to a billing account
- The
gcloudCLI installed - A domain name (as created earlier in the semester for free via the GitHub Student Developer Pack)
- Your locallibrary app pushed to a Git repo you can clone on the VM
1. Prepare locallibrary for deployment
Do this on your laptop, in your locallibrary repo, before touching Google Cloud.
Add production dependencies
Production needs a Postgres driver and a WSGI server that your laptop doesn’t. Put them in a prod dependency group so they only install inside the Docker image:
uv add --group prod "psycopg[binary]" gunicornYou do not need to add Daphne or channels-redis here: the Channels tutorial already added both as regular dependencies.
Add WhiteNoise, which serves your CSS and JavaScript in production. It goes in the regular dependencies, not the prod group, because settings.py refers to it and has to load on your laptop too:
uv add whitenoiseUpdate settings.py
In settings.py, replace the DATABASES dict:
DATABASES = {
"default": env.db(default=f"sqlite:///{BASE_DIR / 'db.sqlite3'}")
}This gives you SQLite on your laptop (no setup, no Postgres install) and Postgres on the server (configured automatically by Docker Compose via the DATABASE_URL environment variable).
Also replace ALLOWED_HOSTS and CSRF_TRUSTED_ORIGINS:
ALLOWED_HOSTS = env.list("ALLOWED_HOSTS", default=["localhost", "127.0.0.1"])
CSRF_TRUSTED_ORIGINS = env.list("CSRF_TRUSTED_ORIGINS", default=[])Finally, add the proxy header so Django knows requests arrive over HTTPS:
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")Without this line, you will get CSRF errors on login and redirect loops if SECURE_SSL_REDIRECT is on.
Set where collectstatic puts your static files. The Dockerfile runs it during the build, and without this setting the build fails:
STATIC_ROOT = BASE_DIR / "staticfiles"Then add WhiteNoise to MIDDLEWARE, directly after SecurityMiddleware:
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware",
# ...the rest unchanged
]With DEBUG=False, Django stops serving static files, so without WhiteNoise your deployed site loads with no CSS.
Add a Dockerfile
Copy Dockerfile.example into your locallibrary repo as Dockerfile. If you copied it before October 15, make sure its collectstatic line now reads:
RUN REDIS_URL=redis://build-placeholder:6379 python manage.py collectstatic --noinputThe build runs collectstatic, which loads settings.py, and your .env is not in the image. The placeholder only satisfies env("REDIS_URL") during the build; the running app gets the real address from Docker Compose.
Then replace its CMD line with this one, which runs Daphne so Channels works:
CMD ["sh", "-c", "python manage.py migrate --noinput && exec daphne -b 0.0.0.0 -p 8000 locallibrary_config.asgi:application"]Commit and push
Make sure everything still works locally (uv run python manage.py runserver), then commit and push:
git add pyproject.toml uv.lock Dockerfile settings.py
git commit -m "Add production config for Google Cloud deployment"
git pushFrom here on, everything happens in Google Cloud.
2. Create your Google Cloud project
Authenticate and create a project. Use cs347f26-YOUR_EID as the project ID:
gcloud auth login
gcloud projects create cs347f26-YOUR_EID --name="CS 347 - YOUR_EID"
gcloud config set project cs347f26-YOUR_EIDThen link your billing account so you can enable Compute Engine. List your billing accounts to find the ID:
gcloud billing accounts listCopy the account ID (format XXXXXX-XXXXXX-XXXXXX) and enter it in the “Billing Account ID” field above, then link it to your project (you probably want the one whose name is Billing Account for Education):
gcloud billing projects link cs347f26-YOUR_EID --billing-account=BILLING_ACCOUNT_ID3. Create your VM
On your laptop, clone this repository and run the setup script with your JMU eID as follows. If you are on Windows, NOTE: run the create-vm.sh script below from something other than Command Prompt and other than PowerShell (e.g. from git bash. probably you should attempt to remember this in general for files whose names end in .sh)
git clone https://github.com/CS-347-F26/google-cloud.git
cd google-cloud
./create-vm.sh YOUR_EIDThe script creates a static IP address, opens ports 80 and 443, and launches a Debian VM that installs Docker automatically on first boot. It prints your static IP when it finishes — enter it in the “Static IP” field above. The DNS and SSH commands below will update with your IP.
If you lose track of your static IP later, print it again with:
gcloud compute addresses describe cs347-YOUR_EID-ip --region us-central1 --format='value(address)'Wait about 60 seconds for the startup script to finish installing Docker. You can watch it:
gcloud compute ssh cs347-YOUR_EID --zone us-central1-c \
--command 'sudo journalctl -u google-startup-scripts -f'4. Set up DNS
At your domain registrar, add one wildcard A record:
*.yourdomain.dev A YOUR_STATIC_IP10. — that is an internal IP. Use the external IP that the script printed.This single record covers every app you will ever add. Verify it resolves before continuing: open MxToolbox DNS Lookup, choose A Lookup, and look up this hostname:
library.yourdomain.devThe result should show your static IP. If it finds no record, wait a few minutes and try again. Do not start the containers until DNS is working — Caddy requests a TLS certificate on first contact with each hostname, and that fails if DNS is not live yet.
5. SSH into your VM
gcloud compute ssh cs347-YOUR_EID --zone us-central1-cThe first time you log in, the VM adds you to the docker group. Log out and back in once for that to take effect:
exit
gcloud compute ssh cs347-YOUR_EID --zone us-central1-cVerify Docker works without sudo:
docker psYou should see something like:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
Set up SSH config for direct access
gcloud compute ssh works, but you can also configure plain ssh, scp, and rsync to connect directly. First, find your OS Login username:
gcloud compute os-login describe-profile --format='value(posixAccounts[0].username)'It will look something like stewarmc_jmu_edu. Paste it into the “OS Login Username” field above.
Add an entry to ~/.ssh/config on your laptop:
Host cs347-YOUR_EID
HostName YOUR_STATIC_IP
User YOUR_OS_LOGIN_USERNAME
IdentityFile ~/.ssh/google_compute_engineNow you can use standard tools from your laptop, e.g.:
- Get an interactive terminal:
ssh cs347-YOUR_EID -
Copy files to the VM:
scp WHATEVER_FILES cs347-YOUR_EID:/whatever/path/ -
Or sync an app directory:
rsync -av WHATEVER_DIR/ cs347-YOUR_EID:/WHATEVER_REMOTE_DIR/
FYI: The key at ~/.ssh/google_compute_engine was created by your first gcloud compute ssh.
6. Clone the deployment files and locallibrary
Copy the deployment files (Dockerfile.example, docker-compose.yml, Caddyfile, init-databases.sql,
env.example) into /srv/apps/. By running the following form your laptop:
scp Dockerfile.example docker-compose.yml Caddyfile init-databases.sql env.example cs347-YOUR_EID:/srv/appsNext ssh to the server and move to the directory where you just put those files
ssh cs347-YOUR_EID
cd /srv/appsThen clone locallibrary beside them:
git clone YOUR_LOCALLIBRARY_REPO locallibraryYour /srv/apps/ directory should look like this:
.env ← you create this next
Caddyfile
Dockerfile.example
docker-compose.yml
env.example
init-databases.sql
locallibrary/ ← your app repo
7. Configure your environment
cp env.example .env
nano .envFill in your values:
| Variable | What to put |
|---|---|
SECRET_KEY | A long random string (run python3 -c "import secrets; print(secrets.token_urlsafe(50))") |
ACME_EMAIL | Your email (for Let’s Encrypt expiry warnings) |
LOCALLIBRARY_HOST | library.yourdomain.dev |
KAHDUKE_HOST | kahduke.yourdomain.dev |
FINAL_PROJECT_HOST | finalproject.yourdomain.dev |
ALLOWED_HOSTS | .yourdomain.dev |
CSRF_TRUSTED_ORIGINS | https://*.yourdomain.dev |
POSTGRES_PASSWORD | A strong password (only used internally between containers) |
Fill in KAHDUKE_HOST and FINAL_PROJECT_HOST now even though those apps are not deployed yet. Caddy reads all three hostnames: leaving one blank or deleting it stops Caddy from starting at all, and leaving the placeholders in makes it try to get certificates for a domain you do not own. Each hostname must be different.
Do not set DATABASE_URL in .env. Leaving it unset is what makes SQLite work on your laptop.
8. Start locallibrary
library.yourdomain.dev resolving to YOUR_STATIC_IP. If DNS is not live, Caddy fails to get your TLS certificates, and repeated failures can get you rate-limited by Let’s Encrypt.settings.py defines STATIC_ROOT (see step 1). I have changed Part 2 of the Channels tutorial since you completed it, so your settings may be missing it. This diff shows exactly what changed.docker compose up -d --build caddy locallibraryThis builds the locallibrary image, starts Postgres and Redis, runs your migrations, and starts Caddy. Name the two services as shown: a bare docker compose up would also try to build kahduke and final_project, which you have not cloned, and fail. On first launch it takes a few minutes because it is downloading base images and building from scratch.
Check that everything is running:
docker compose ps
docker compose logs -fOnce Caddy has obtained a certificate (you will see log lines about it), visit your app at https://library.yourdomain.dev.
9. Create a superuser
Your deployed site has a fresh Postgres database, so none of your local users exist there. From /srv/apps on the VM, create an admin account:
docker compose exec locallibrary python manage.py createsuperuserThen log in at https://library.yourdomain.dev/admin/.
me/me. That was fine on your laptop, but this site is on the public internet, and bots start trying common usernames and passwords on new sites within hours. Use a real username and a long, randomly generated password.Save that password in a password manager. As a student you can get 2 years of 1Password free, and it is excellent. These days, a big part of a software developer’s job is holding the keys and temporarily granting one AI permission to talk to another AI. It would suck to be bad at holding the keys.
Deploying updates
After pushing changes to your locallibrary repo:
gcloud compute ssh cs347-YOUR_EID --zone us-central1-c
cd /srv/apps
git -C locallibrary pull
docker compose up -d --build locallibraryMigrations run automatically on container start, so there is no separate step for that.
Backups
Dump all your databases to a file:
docker compose exec postgres pg_dumpall -U cs347 > ~/backup-$(date +%F).sqlThe Postgres data volume survives docker compose down, reboots, and rebuilds. It does not survive docker compose down -v — that flag deletes all volumes, including your databases. Do not use it.
Troubleshooting
Reading the logs
Most problems show up in a container’s logs. SSH to your VM and run these from /srv/apps.
First, check which containers are running. A container showing Exited or Restarting has crashed, and its logs say why:
docker compose ps -aCaddy logs certificate problems (DNS, Let’s Encrypt) and failures to reach your app:
docker compose logs --tail 50 caddyDjango (the locallibrary container) logs migration errors at startup, each request, and Python tracebacks:
docker compose logs --tail 100 locallibraryTo watch logs live while you reload the page in your browser, add -f and press Ctrl+C to stop:
docker compose logs -f caddy locallibraryBuild errors (for example, a failing collectstatic) are not in the logs. They print in the output of the docker compose up -d --build command itself, so scroll up in that output.
With DEBUG=False, Django does not print tracebacks by default: a page shows “Server Error (500)” and the log shows only the request. Add this to the bottom of settings.py so errors appear in docker compose logs, then commit, push, and rebuild:
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"handlers": {"console": {"class": "logging.StreamHandler"}},
"root": {"handlers": ["console"], "level": "WARNING"},
}Common problems
| Problem | Likely cause |
|---|---|
| Browser says it cannot connect (no error page at all) | Caddy is not running. Run docker compose ps -a; if caddy is missing or exited, see docker compose logs caddy and re-run docker compose up -d --build caddy locallibrary |
caddy shows Restarting in docker compose ps | A bad value in .env. Run docker compose logs --tail 5 caddy and match the error:server block without any key is global configuration → a *_HOST variable is blank or missingambiguous site definition → two *_HOST variables have the same value, or one contains a spacewrong argument count … after 'email' → ACME_EMAIL is blankFix .env, then run docker compose up -d caddy |
| 502 Bad Gateway | Caddy is up but locallibrary is not. Check docker compose logs locallibrary for a crash or a failed migration |
| “Server Error (500)” | A Python exception. Find the traceback with docker compose logs locallibrary (requires the LOGGING setting) |
| CSRF errors on login | Missing SECURE_PROXY_SSL_HEADER in settings.py |
| Infinite redirect loop | SECURE_SSL_REDIRECT = True without SECURE_PROXY_SSL_HEADER |
Build fails at collectstatic | Missing STATIC_ROOT in settings.py |
Build fails with Set the REDIS_URL environment variable | Your Dockerfile has the old collectstatic line; update it |
| Redis connection errors / chat does not work | CHANNEL_LAYERS still says 127.0.0.1 instead of reading REDIS_URL (see Channels tutorial Part 2) |
| Site loads with no CSS | WhiteNoise not in MIDDLEWARE |
| TLS / certificate errors | DNS not resolving yet, or port 80 is blocked |
Killed during docker compose build | The swap file is missing — check that the startup script ran |
| Browser refuses plain HTTP | .dev domains are HSTS-preloaded; you must use https:// |
New database not created after editing init-databases.sql | That file only runs once; use docker compose exec postgres createdb -U cs347 dbname |
Tearing down
When the semester is over, the cleanest way to remove everything is to delete the entire project:
gcloud projects delete cs347f26-YOUR_EIDThis removes the VM, disk, and static IP in one step.