0

I'm working on a project with python where I want to automate docker containers creation. I have the project folder already with includes all the files required to create the image.

One of these is create_image.sh

docker build -t my_container:latest .

Currently I do:

sudo bash create_image.sh

But now I need to automate this process from python. I have tried:

import os
import subprocess
subprocess.check_call("bash -c '. create_image.sh'", shell=True)

But I get this error:

CalledProcessError: Command 'bash -c '. create_image.sh'' returned non-zero exit status 1.

EDIT:

The use case is to automate containers creation through an API, I have the code in flask and python until this point, where I got stuck in the images creation from the docker file. The rest is automated from templates.

Luis Ramon Ramirez Rodriguez
  • 9,591
  • 27
  • 102
  • 181

2 Answers2

3

You can try:

subprocess.call(['sudo', 'bash', 'create_image.sh' ])

which is equivalent of

sudo bash create_image.sh

Note: Let me say that there are better ways of automating docker container creation - please check docker-compose which can build and start the container easily. If you can elaborate more on the use case, we could help you with an elegant solution for docker. It might not be a python problem

EDIT: Following the comments, it would be better to create a docker-compose and makefile is used to issue docker commands. Inspiration - https://medium.com/@daniel.carlier/how-to-build-a-simple-flask-restful-api-with-docker-compose-2d849d738137

hrmnjt
  • 183
  • 7
  • Thanks! I just added some details to the question – Luis Ramon Ramirez Rodriguez Sep 11 '19 at 21:04
  • 1
    I would suggest you to create a docker-compose and makefile. Whenever you need to run a particular docker function you could use make commands to do that - triggered by the API – hrmnjt Sep 11 '19 at 21:09
  • 1
    Reasoning for suggesting the solution - http://datakurre.pandala.org/2016/04/evolution-of-our-makefile-for-docker.html/ – hrmnjt Sep 11 '19 at 21:10
  • 1
    @luis-ramon-ramirez-rodriguez Or you can read this blog towards the last section - https://medium.com/@daniel.carlier/how-to-build-a-simple-flask-restful-api-with-docker-compose-2d849d738137 – hrmnjt Sep 11 '19 at 21:11
1

In case that's because your user can't run docker without sudo, probably it's better to grant him docker API access by including him to docker group: https://askubuntu.com/questions/477551/how-can-i-use-docker-without-sudo

Simply adding user to docker group:

sudo gpasswd -a $USER docker

Also if You want to automate docker operations on python, I'd recommend to use python library for docker: How to build an Image using Docker API Python Client?