DEV Community

realninety5
realninety5

Posted on

How to deploy a Django Docker container to Elastic Beanstalk

You can easily deploy your Django application to Elasticbeastlk (EB) by following these simple steps.

Note, while creating your application, add
Also ensure you have the Elastic Beanstalk cli 'eb' installed on your local machine.



0.0.0.0


Enter fullscreen mode Exit fullscreen mode

to your ALLOWED_HOSTS in your application settings.py, also add this line



import os
live = os.getenv("LIVE")


Enter fullscreen mode Exit fullscreen mode

Add "live" to your ALLOWED_HOSTS too, we will update it with the URL elastic beanstalk will provide us later.

Create a file with the list of requirements for the application to run by running



pip freeze > requirements.txt


Enter fullscreen mode Exit fullscreen mode

Create your Dockerfile




# the base image to run your application
FROM python:3.8.10-slim

# setup environment variable
ENV DockerHOME=/home/app/webapp

# set work directory
RUN mkdir -p $DockerHOME

# where your code lives
WORKDIR $DockerHOME

# set environment variables

# this ensures that the Python interpreter doesn’t generate .pyc files, we don't need them
ENV PYTHONDONTWRITEBYTECODE 1
# this will send python output straight to the terminal(standard output) without being buffered
ENV PYTHONUNBUFFERED 1

# install dependencies
RUN pip install --upgrade pip

# copy the whole project to your docker home directory.
COPY . $DockerHOME
# run this command to install all dependencies
RUN pip install -r requirements.txt
# port where the Django app runs
EXPOSE 5000
# start the server on port 5000, this is what EB listens for
CMD ["python", "manage.py", "runserver", "0.0.0.0:5000"]



Enter fullscreen mode Exit fullscreen mode

On your local machine, you can test your EB deployment by running



eb inti -p docker _application_name_


Enter fullscreen mode Exit fullscreen mode

and run it with



eb local run --port 5000


Enter fullscreen mode Exit fullscreen mode

To deploy the application, run



eb create _environment_name_


Enter fullscreen mode Exit fullscreen mode

and follow the prompts

When you are done, use



eb open


Enter fullscreen mode Exit fullscreen mode

to open the application

If this tells you to add the URL to ALLOWED_HOSTS, copy the URL and add it to "software" with the name "live" (as we mentioned above) in "configuration" under the environment tab like so.

Image description

Top comments (0)