简体   繁体   中英

Create and build docker Dockerfile from a script

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 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?

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.)

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