Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

docker permissions issue writing to txt file with simple python script

why do I need permission to write to a txt file? How do I solve this problem

main.py

text_file = open("sample.txt", "w")
n = text_file.write('some words dzfsadfadfs')
text_file.close()

Dockerfile

FROM rayproject/ray
ADD main.py .
CMD ["python", "main.py"]

error

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    text_file = open("sample.txt", "w")
PermissionError: [Errno 13] Permission denied: 'sample.txt'
question from:https://stackoverflow.com/questions/65884838/docker-permissions-issue-writing-to-txt-file-with-simple-python-script

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that the base image you're using (rayproject/ray) is configured to run as a non-root user (ray), but sets the working directory to /. There is a writeable directory /home/ray available; the easiest solution is probably adding an appropriate WORKDIR directive to your Dockerfile:

FROM rayproject/ray
WORKDIR /home/ray
ADD main.py .
CMD ["python", "main.py"]

Update

I figured this out by first spawning a shell and checking what uid the process was running as:

$ docker run -it --rm testimage bash
(base) ray@bca6b7788820:~$ id
uid=1000(ray) gid=100(users) groups=100(users),27(sudo)

I checked the passwd file for information about that user:

(base) ray@bca6b7788820:~$ grep ray /etc/passwd
ray:x:1000:100::/home/ray:/bin/bash

And verified that directory was writeable:

(base) ray@bca6b7788820:~$ cd /home/ray
(base) ray@bca6b7788820:~$ touch foo

In general you can also figure things like this out by inspecting the corresponding Dockerfile, but for this particular base image that ended up being a bit of a pain because you need to track down a chain of dependencies:

And if you look at that last Dockerfile, you find:

USER $RAY_UID
ENV HOME=/home/ray

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...