I’m working on a Discord bot with a friend of mine which runs on Python. I’m quite unfamiliar with the language but it bothered me that each time I make a change in code, I need to to restart the bot completely. I did some research and it didn’t seem like there were a lot of standard solutions. The best way to go seems to be unrelated to Python, instead i’m advised to use Node with Nodemon.
To better understand what i’m dealing with I decided to start from scratch.
- Create or find a Dockerfile that fully supports Python and NPM
- Integrate this into a docker-compose setup
- Start the script on docker-compose up
- Restart the script when a file change is detected
A quick search led me to
nikolaik/python-nodejs:latest Dockerfile. Let’s use that as a starting point. The only thing we have to do is extend it with nodemon. We’ll add this file in the root directory as “Dockerfile”.
FROM nikolaik/python-nodejs:latest RUN npm install -g nodemon
The docker-compose setup
version: "3" services: python: container_name: python-restart-test build: context: . command: python app.py && tail -f /dev/null working_dir: /app volumes: - ./:/app/
This will run the app.py file upon start. For now, we’ll add this to the file:
import os print("test123")
docker-compose up everything runs fine, “test” is printed in the logs and the container is exited.
Let’s dive into nodemon now. According to this StackOverflow post we can use nodemon as
nodemon app.py. Let’s integrate this into the docker-compose.yml file.
version: "3" services: python: container_name: python-restart-test build: context: . image: nikolaik/python-nodejs:latest command: nodemon app.py working_dir: /app volumes: - ./:/app/ networks: default: external: name: nginx-proxy
Okay, that works. Now the actual app imports some other files and we need nodemon to watch these files as well. I’ll add a folder called ‘inc’ and add 2 .py files here.
Well, apparently nodemon watches subdirectories as well. Looks like we’re good to go!
All files in this project