From your question, you want to have code that creates a docker container, and then in the same file have code that is only executed inside the docker container.
Which is possible using the following setup:
dockerfile
FROM python:3.8-slim-buster
WORKDIR /src
COPY requirements.txt requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
ENV AM_I_IN_A_DOCKER_CONTAINER=True
CMD [ "python", "-m" , "main"]
main.py
import os
import subprocess
if __name__ == '__main__':
# https://stackoverflow.com/questions/43878953/how-does-one-detect-if-one-is-running-within-a-docker-container-within-python
SECRET_KEY = os.environ.get('AM_I_IN_A_DOCKER_CONTAINER', False)
if not SECRET_KEY:
print(f"Code running to create container.")
process = subprocess.Popen(["docker", "build", "--tag", "stackoverflow-question", "."])
process.wait(timeout=60)
process.terminate()
print(f"Created image: 'stackoverflow-example'")
process = subprocess.Popen(["docker", "run", "--publish", "5000:5000", "stackoverflow-question"])
process.wait(timeout=60)
print(f"Created container: 'stackoverflow-example'")
print(f"Terminating primary script.")
exit()
import numpy as np
print(f"\nWelcome inside the container.")
print(f"This will be running inside the container only.")
print(np.random.randint(1, 255, 10))
requirements
numpy
Process
The process is performed in two steps.
Firstly, we need to execute code that will create the docker image and launches the container. The above code uses subprocess
to create a new image that contains the main.py
and the requirements.txt
file. Then in the container we also specify that it should run the main.py
file.
Secondly we have to distinguish what code from main.py
we are running inside and outside the container. This is done by using a post from Kyle Truong (43878953), which is the variable AM_I_IN_A_DOCKER_CONTAINER
. Now we can split the main.py
file in a section to run before the container, and after the container.
Side note
This code will launch one new docker container on every run so be sure to close them.