Home > Blockchain >  How to use GCP service account json files in Docker
How to use GCP service account json files in Docker

Time:08-24

I am dockerizing Fastapi application which is using Firebase. I need to access service json file and I have configured my docker container as follows.

Dockerfile

FROM python:3.10-slim

ENV PYTHONUNBUFFERED 1

WORKDIR /app

# Install dependencies
COPY ./requirements.txt /requirements.txt
EXPOSE 8000

RUN pip install --no-cache-dir --upgrade -r /requirements.txt
   
RUN mkdir /env
# Setup directory structure
COPY ./app /app/app
COPY ./service_account.json /env
CMD ["uvicorn", "app.app:app", "--host", "0.0.0.0", "--port", "8000"]

Docker-compose file

version: "3.9"

services:
  app:
    build:
      context: .
    restart: always
    environment:
      - GOOGLE_APPLICATION_CREDENTIALS_CLOUDAPI=${GOOGLE_APPLICATION_CREDENTIALS_CLOUDAPI}
      - GOOGLE_APPLICATION_CREDENTIALS=${GOOGLE_APPLICATION_CREDENTIALS}
    volumes:
      - ./env:/env

volumes:
  env:

Now when I run docker-compose up -d --build the container fails with the error FileNotFoundError: [Errno 2] No such file or directory: '/env/service_account.json'. When I inspect the container I can see the ENV variable set successfully as shown "GOOGLE_APPLICATION_CREDENTIALS=/env/service_account.json",. Now why is this failing?

CodePudding user response:

You have context: . and COPY ./service_account.json /env

But when you run the container, you have

volumes:
   - ./env:/env

Meaning your service_acccount file is not in ./env folder, and is instead outside of it.

When you mount a volume, it replaces the directory inside the container, so if you need a local env folder mounted as /env in the container, then you should move your JSON file somewhere else such as /opt (COPY ./service_account.json /opt), and then set GOOGLE_APPLICATION_CREDENTIALS=/opt/service_account.json

If you don't need the whole folder, then you only need

volumes:
   - ./service_account.json:/env/service_account.json:ro

Otherwise, move the JSON file into ./env on your host and change COPY ./env/service_account.json /env

  • Related