Bob van Luijt
Bob van Luijt

Reputation: 7588

How to connect to a SQL instance in an App Engine custom runtime Dockerfile?

There is a lot of documentation but not specific about Dockerfiles (or I missed it).

My app.yaml file:

runtime: custom
env: flex
env_variables:
  MYSQL_DSN: mysql:unix_socket=/cloudsql/project-name:europe-west1:test001;dbname=db001
  MYSQL_USER: root
  MYSQL_PASSWORD: 'qwerty'

My Dockerfile:

FROM ubuntu:16.04

ARG dbuser
ENV dbuser ${MYSQL_USER}
ARG dbpass
ENV dbpass ${MYSQL_PASSWORD}
ARG dbhost
ENV dbhost ${MYSQL_DSN}

RUN apt-get update
RUN apt-get install mysql-client
RUN mysql -h ${dbhost} -u ${dbuser} -p${dbpass} -e "CREATE DATABASE 'test';"

Documentation followed:

Upvotes: 1

Views: 601

Answers (1)

David
David

Reputation: 9721

The mysql command line does not understand the DSN syntax you are passing. The socket and database must be passed in separately.

Additionally "RUN" entries in your Dockerfile are run when building the docker image, before it is actually ran in your App. As a result it doesn't have the environment available to it. Moreover you probably don't want to be configuring or accessing a remote database when building an image.

Here's an alternative:

app.yaml

runtime: custom
env: flex
env_variables:
  MYSQL_SOCK: /cloudsql/project-name:europe-west1:test001
  MYSQL_DB: db001
  MYSQL_USER: root
  MYSQL_PASSWORD: 'qwerty'

your_program.sh

#!/bin/sh
mysql -S $MYSQL_SOCK -u $MYSQL_DB -p$MYSQL_PASSWORD $MYSQL_DB -e "CREATE DATABASE 'test';"

Dockerfile

FROM ubuntu:16.04

RUN apt-get update
RUN apt-get install mysql-client
CMD ["your_program.sh"]

Upvotes: 2

Related Questions