Home > database >  Unable to access JSON file through shell script inside docker container
Unable to access JSON file through shell script inside docker container

Time:03-05

I'm trying to populate data using REST endpoints of another container (i.e. my-blog-container) by creating a container (data-loader), for which I'm running a shell script dataloader.sh inside container (i.e. data-loader). In the shell script I'm trying to access the json file (i.e. mydata.json) to make the POST call in shell script while running the container.

Basically Goal is to populate the data by spinning up the container on its own.

But I'm getting an error in my container:

Warning: Couldn't read data from file 
Warning: "mydata.json", this makes an empty
Warning: POST.

docker-compose.yaml

  data-loader:
    <<: *my-base-service
    build:
      context: .
      dockerfile: Dockerfile.dataloader
      args:
        IMAGE_NAME: <alpine base image>
    container_name: data-loader
    volumes:
      - $MY_PATH/config/mydata.json

Dockerfile.dataloader

ARG IMAGE_NAME
FROM ${IMAGE_NAME}

USER root
RUN apk update && apk upgrade && apk add curl
COPY dataloader.sh /
RUN chmod  x /dataloader.sh

ENTRYPOINT [ "sh", "/dataloader.sh" ]

dataloader.sh

response=$(curl -X POST "http://myblogcontainer:8080/blog/create" -H "accept: */*" -H "Content-Type: application/json" \
       -d @mydata.json)
echo ${response}

I want to populate the data using this json file. But unable to make it. Please help me out.

If you have any questions, please feel free to ask. Thanks in advance :)

CodePudding user response:

Given the assumption that you have a colon as part of MY_PATH, you mount the file into /config/ but you are using a relative path in your script.

If your workdir is not /config, then your script will not find the file. To be sure you could use an absolute path.

-d '@/config/mydata.json'

In general, it is useful in these kinds of scenarios to do some debugging by entering the container interactively to poke around in the file system. Or by adding some print statements to your script to ensure your assumptions are correct.

Also note that your script is missing a shebang. The default interpreter is actually sh, so it works out, but it is good practice to add one anyway.

You probably should also double quote the variable response when using to prevent word splitting and globbing.

  • Related