Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serving Django static files in Elasticbeanstalk Docker environment

When deploying a Django application to EB using docker environment, static files are returning 404.

I'm using gunicorn on docker container, and since it's not recommended/not possible(?) to serve static files via gunicorn, I want to configure EB nginx to serve them using host file-system.

Dockerfile

FROM python:3
....
....
# Expose listen ports
EXPOSE 8002

RUN chmod +x ./docker/container_start.sh

CMD ["sh", "./docker/container_start.sh"]

Dockerrun.aws.json

{
  "AWSEBDockerrunVersion": "1",
  "Ports": [
    {
      "ContainerPort": "8002"
    }
  ],
  "Volumes": [
    {
      "ContainerDirectory": "/app/assets",
      "HostDirectory": "/var/app/current/assets"
    }
  ]
}

How could I tell EB nginx to serve /assets/* from /var/app/current/assets and to proxy the rest to docker container?

Something like below doesn't work because of the docker environment.

option_settings:
  "aws:elasticbeanstalk:container:python:staticfiles":
    "/static/": "www/static/"
like image 774
EastSw Avatar asked May 01 '18 08:05

EastSw


1 Answers

To summarize our solution for serving static files from django running in an elasticbeanstalk docker container with SolutionStackName: 64bit Amazon Linux 2 v3.2.0 running Docker:

  1. We don't want to run collectstatic until our container is really ready to go. To that end we kick it off in our entrypoint.sh, which also starts gunicorn shortly afterwards.
  2. We let collectstatic drop the static files in "static" From our settings:
STATIC_ROOT = "static"
STATIC_URL = "/static/"
  1. We configure a post-deployment script in .platform/hooks/postdeploy that copies the static files out of the container and onto the ec2 vm in /var/app/current (where the script runs):
#! /bin/bash
docker cp $(docker ps --no-trunc -q | head -n 1):/home/app/static .
  1. We tell nginx where to find the static files by dropping a custom configuration file in .platform/nginx/conf.d/elasticbeanstalk/custom.conf :
location /static/ {
    root /var/app/current/;
}

That's it. It works for us.

like image 61
rotten Avatar answered Oct 14 '22 04:10

rotten