Home > other >  PHP WebServer hosted in Google Cloud Run environment: persist files (images)
PHP WebServer hosted in Google Cloud Run environment: persist files (images)

Time:02-10

I have built and deployed a PHP-based website hosted in a Google Cloud Run container where images sit in a /images folder and a link to each image is stored in a MySQL database hosted in a Google Cloud VM. All this works well.

Now I'm working on an admin function to upload images to the web server. There are plenty of resources available for uploading images (and I've developed a similar solution before) including PHP handling file uploads. So no perceived issues there.

My challenge is that any files (images) uploaded to the web server will be destroyed when I redeploy my code to the container (content is wiped when the container is stopped).

I found this resource which suggests that Google Cloud Storage would be an appropriate solution. What I can't find, though, is any guidance on how to connect my Google Cloud Run instance to a Google Cloud Storage location, or how to point a folder within the Google Cloud Run instance to Google Cloud Storage. I can see that Firestore is another option. Cloud SQL is not an option for me as I don't wish to store the images in the database (though I could if this were considered the best option for my environment).

Ironically, Google (the search engine) is not being my friend here and I'm struggling to find guidance on how to go about achieving my objective. Are you aware of a resource the explains at least the basics of how to do this?

CodePudding user response:

An approach you can consider is to mount Google Cloud Storage buckets using gcsfuse.

Mounting a file system allows for sharing resources between a host system and container instances and for resources to persist after a container instance is garbage collected.

Here's a sample Dockerfile:

# https://github.com/chiaen/docker-gcsfuse
FROM golang:1.17.5-alpine as gcsfuse
RUN apk add --no-cache git
ENV GOPATH /go
RUN go get -u github.com/googlecloudplatform/gcsfuse

FROM composer:2 as vendor
COPY composer.json composer.json
COPY composer.lock composer.lock
RUN composer install --ignore-platform-reqs --no-interaction --prefer-dist

FROM craftcms/nginx:7.4

ENV MNT_DIR /mnt/gcs

USER root
RUN apk add --no-cache mysql-client postgresql-client ca-certificates fuse nano sudo tini bash
RUN mkdir -p $MNT_DIR
RUN chown www-data:www-data $MNT_DIR

COPY --chown=www-data:www-data --from=vendor /app/vendor/ /app/vendor/
COPY --chown=www-data:www-data . .
COPY --from=gcsfuse /go/bin/gcsfuse /usr/local/bin
COPY supervisor.conf /etc/supervisor/conf.d/supervisor.conf
  •  Tags:  
  • Related