[Python] Using python subprocess to restart a docker container from within a different one

Discussão em 'Python' iniciado por Stack, Fevereiro 5, 2025.

  1. Stack

    Stack Membro Participativo

    Here is my mc_restart.py:

    result = subprocess.run(
    "docker restart mc",
    shell=True, # Run in a shell to handle built-ins like cd
    stdout=subprocess.PIPE, # Capture standard output
    stderr=subprocess.PIPE, # Capture standard error
    check=True # Raise an error if the command fails
    )


    I have mounted docker.sock in my compose:

    volumes:
    - /mnt/docker/mc_docker:/mnt/docker/mc_docker
    - /var/run/docker.sock:/var/run/docker.sock


    And my dockerfile to create a user to run commands:

    RUN apt-get update && apt-get install -y \
    docker.io \
    && apt-get clean
    RUN adduser --disabled-password --gecos "" myuser
    RUN groupadd -f docker && usermod -aG docker myuser
    WORKDIR /app
    COPY . .
    RUN pip install --no-cache-dir -r requirements.txt
    USER myuser
    ENV PYTHONUNBUFFERED=1
    CMD ["python", "./mc_restart.py"]


    And finally, the error I get when I run my container:

    mc_restart | Error stopping docker container: permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post "http://%2Fvar%2Frun%2Fdocker.sock/v1.24/containers/mc/restart": dial unix /var/run/docker.sock: connect: permission denied


    I have tried running it without creating myuser and tried different commands like docker stop mc but keep running into this permission error. I know docker.io is an old installation but I'm not sure how to install the latest docker and if it would make a difference.

    Continue reading...

Compartilhe esta Página