skip to Main Content

I’m trying to import the content of a .json file and run it in a Docker container, but I get next error when run the docker container:

Error:

Traceback (most recent call last):
File "/stockalert-app/./app/main.py", line 22, in <module>
  main()
File "/stockalert-app/./app/main.py", line 17, in main
  data = importData('data.json')
File "/stockalert-app/./app/main.py", line 10, in importData
  with open(fileName) as json_file:
FileNotFoundError: [Errno 2] No such file or directory: 'data.json'

This is my project structure:

├── stockalert
    ├── app
    │   ├── main.py
    │   ├── data.json
    ├── requirements.txt
    ├── Dockerfile

main.py

import json

def importData(fileName):
    with open(fileName) as json_file:
        data = json.load(json_file)    
    return data


def main():
    data = importData('data.json')
    print("Data: ")
    print(data)

if __name__ == "__main__":
    main()

Dockerfile

FROM python:3

WORKDIR /stockalert-app

COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt

COPY ./app ./app

CMD [ "python", "./app/main.py" ]

I understand that I´m doing something wrong but I don´t know that, the code runs well on the host machine, but when runs into a container not, so the question is: Which is the correct way to do it?.

2

Answers


  1. With this Dockerfile instruction WORKDIR /stockalert-app, you’re setting the working directory to /stockalert-app. This means that when you copy the app directory, the absolute path to the json file will be /stockalert-app/app/data.json.

    You have two solutions:

    1. Use WORKDIR /app
    2. Use importData('/app/data.json') (or even better, importData('/stockalert-app/app/data.json')
    Login or Signup to reply.
  2. Your PWD is /stockalert-app and your json file is /stockalert-app/app/data.json.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search