简体   繁体   中英

How do I run Python Docker containers in the background and use them in my commands?

I want to use different Python versions in my tests. I want to have 3 Docker containers for Python 3.6, Python 3.7 and Python 3.8 running and I want the commands python3.6 , python3.7 , python3.8 to be accessible in the environment.

If it can also associate these containers with just python command, that could help as well.

I suppose you mean you want 3 docker containers running, each with a different Python version. And you want to execute commands from the host for each python container.

You can do this with the following scripts:

docker-compose.yml

Create a docker-compose.yml file with the following content:

version: '3.9'

services:

  python36:
    image: python:3.6.14-buster
    container_name: python36
    working_dir: /app
    volumes:
      - ./app:/app
    command: ["sleep", "30d"]

  python37:
    image: python:3.7.11-buster
    container_name: python37
    working_dir: /app
    volumes:
      - ./app:/app
    command: [ "sleep", "30d" ]


  python38:
    image: python:3.8.11-buster
    container_name: python38
    working_dir: /app
    volumes:
      - ./app:/app
    command: [ "sleep", "30d" ]

Python script to run

In a folder called ./app create a file called version.py

import sys

print(sys.version)

Command on the Host

Create a Bash script on the host running the version.py for all three containers. Call it run_command.sh (and 'chmod 755' it of course)

#!/bin/bash

docker exec -it python36 python version.py
docker exec -it python37 python version.py
docker exec -it python38 python version.py

Run it with:

./run_command.sh

output

The output:

$ ./run_command.sh
3.6.14 (default, Jun 29 2021, 21:23:13)
[GCC 8.3.0]
3.7.11 (default, Jun 29 2021, 20:31:06)
[GCC 8.3.0]
3.8.11 (default, Jun 29 2021, 19:54:56)
[GCC 8.3.0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM