Home > Mobile >  how to make the django devserver run everytime i create a docker container, instead of when i build
how to make the django devserver run everytime i create a docker container, instead of when i build

Time:11-03

tldr version: how do i do x everytime i build a container, instead of everytime i build a new image.

im building a very basic docker django example. when i do docker-compose build everything works as i want

version: '3.9'
services:
  app:
    build:
      context: .
    command: sh -c "python manage.py runserver 0.0.0.0:8000"
    ports:
      - 8000:8000
    volumes:
      - ./app:/app
    environment:
      - SECRET_KEY=devsecretkey
      - DEBUG=1

this runs the django devserver, however only when the image is being built. the containers created by the image do nothing, but actually i want them to run the django devserver. So i figure i should just move the command: sh -c "python manage.py runserver 0.0.0.0:8000" from docker-compose to my dockerfile as an entrypoint.

below is my docker file

FROM python:3.9-alpine3.13
LABEL maintainer="madshit.com"
ENV PYTHONUNBUFFERED 1
COPY ./requirements.txt /requirements.txt
COPY ./app /app
WORKDIR /app
EXPOSE 8000
RUN python -m venv /py && \
  /py/bin/pip install --upgrade pip && \
  /py/bin/pip install -r /requirements.txt && \
  adduser --disabled-password --no-create-home app
ENV PATH="/py/bin:$PATH"
USER app
ENTRYPOINT python manage.py runserver # i added this because i thought it would be called everytime my docker environment was finished setting up. no dice :(

The bottom section of the image below is a screenshot of the logs of my image from docker desktop. strangely the last command it accepted was to set the user not anything to do with entrypoint. maybe it ignored entrypoint and thats the problem? The top section shows the logs of the instance created from this image (kinda bare).

enter image description here

  1. what do i need to do to make the django webserver run in each container when deployed?

  2. why doesnt entrypoint seem to get called? (its not in the logs)

CodePudding user response:

I would recommend changing your environment variable logic slightly.

environment:
  - SECRET_KEY=devsecretkey
  - DEBUG=1 <-- replace this
  - SERVER='localhost' <-- or other env like staging or live

And then in your settings file you can do:

SERVER = os.environ.get('SERVER')

And then you can set variables based on the string like so:

if SERVER == 'production':
    DEBUG = FALSE
else:
    DEBUG = True

This is a very regular practice so that we can customise all kinds of settings and there are plenty of use cases for this method.

If that still doesn't work, we may have to look at other issues that might be causing these symptoms.

  • Related