1

I am having some difficulty trying to create a script which creates and builds a docker file that gets the current users uid and gid and sets the user vagrant's uid and gid inside of container to match the host.

output = "FROM %s\nUSER root\nRUN usermod --uid %s vagrant && groupmod --gid %s vagrant && chown -R vagrant:vagrant /home/vagrant\nUSER vagrant" % (build_image, uid, gid)
f = open("Dockerfile", "w")
f.write(output)
f.close

# Build the image using the created Dockerfile
build_command = "docker build -t %s . --pull" % args.name
print("\nRunning: " + build_command)
subprocess.call(['bash', '-c', build_command])

docker build -t test-image . --pull works on the command line but when running the script I get: "Error response from daemon: the Dockerfile (Dockerfile) cannot be empty"

Does anyone have any ideas why this might be happening?

6
  • 2
    As an aside, passing a string to ['bash', '-c', cmd] is just a roundabout way of reimplementing cmd, shell=True. You want to avoid both; pass ['docker', 'build', '-t', args.name, '.', '--pull'] directly. Commented Oct 19, 2018 at 12:20
  • Are you maybe in a different working directory on the Command Line compared to the script? Commented Oct 19, 2018 at 12:22
  • @tripleee Thanks that's good to know, I will get that changed Commented Oct 19, 2018 at 12:22
  • @Bernhard No it is all inside of the same directory Commented Oct 19, 2018 at 12:25
  • Is the file created and does it contain what you're expecting? Commented Oct 19, 2018 at 12:30

1 Answer 1

3

You're not actually calling f.close; the result of that line is the uncalled close function itself. A better approach to file handling in Python in general is to use context manager "with" syntax:

with open("Dockerfile", "w") as f:
  f.write(output)

and then the file will be closed for you.

(Actual writes are somewhat expensive, and so Python, like most other languages, will actually keep content to be written in an in-memory buffer until the file is closed, explicitly flushed, or more than a certain amount of content is written, which is why not actually calling f.close() causes a problem.)

Sign up to request clarification or add additional context in comments.

3 Comments

while I agree that the context manager is nicer here: there is an f.close in the code shown? Should it be f.close()?
Thank you this solved the issues, I am still new to python thanks for the clear explanation.
Yes, it needs to be f.close() as written.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.