Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Python script without web server into Docker?

Tags:

python

docker

I have been working with Docker previously using services to run a website made with Django.

Now I would like to know how I should create a Docker to just run Python scripts without a web server and any service related with websited.

An example of normal docker which I am used to work is:

version: '2'
services:
  nginx:
    image: nginx:latest
    container_name: nz01
    ports:
      - "8001:8000"
    volumes:
      - ./src:/src
      - ./config/nginx:/etc/nginx/conf.d
    depends_on:
      - web
  web:
    build: .
    container_name: dz01
    depends_on:
      - db
    volumes:
      - ./src:/src
    expose:
      - "8000"
  db:
    image: postgres:latest
    container_name: pz01
    ports:
        - "5433:5432"
    volumes:
      - postgres_database:/var/lib/postgresql/data:Z
volumes:
    postgres_database:
        external: true

How should be the docker-compose.yml file?

like image 958
mrc Avatar asked Mar 05 '23 10:03

mrc


2 Answers

Simply remove everything from your Dockerfile that has nothing to do with your script and start with something simple, like

FROM python:3

ADD my_script.py /

CMD [ "python", "./my_script.py" ]

You do not need Docker compose for containerizing a single python script.

The example is taken from this simple tutorial about containerizing Python applications: https://runnable.com/docker/python/dockerize-your-python-application

You can easily overwrite the command specified in the Dockerfile (via CMD) when starting a container from the image. Just append the desired command to your docker run command, e.g:

docker run IMAGE /path/to/script.py
like image 115
Thomas Kainrad Avatar answered Apr 04 '23 03:04

Thomas Kainrad


You can easily run Python interactively without even having to build a container:

docker run -it python

If you want to have access to some code you have written within the container, simply change that to:

docker run -it -v /path/to/code:/app: python

Making a Dockerfile is unnecessary for this simple application.

like image 40
Stuart Buckingham Avatar answered Apr 04 '23 03:04

Stuart Buckingham