Problem
If you ssh into your environment and try to connect to your database you will get an error
web@app.0:~$ mysql
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2 "No such file or directory")
That is why the documentation mentions connecting by supplying the parameters from PLATFORM_RELATIONSHIPS.
https://docs.platform.sh/configuration/services/mysql.html#access-your-mariadb-service
For example: mysql -h database.internal -P 3306 -u user main
However, I’d like to show a trick that allows you to simply type mysql
and you will be logged in automatically.
web@app:~$ mysql
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 19
Solution
On your local development go to the source code of your project.
- Create a folder
configs
withmkdir file_mounts
- Create an empty file in that directory
configs/.my.cnf
- Make a link from your root directory to that file
ln -s configs/.my.cnf .my.cnf
- Add the mount folder to git:
git add configs
- Edit the
.platform.app.yaml
file and add a mount point.
mounts:
'configs'
source: local
source_path: 'configs'
- As a final step, add a script that automatically reads your PLATFORM_RELATIONSHIPS, and writes them to a
.my.cnf
:
hooks
deploy: |
set -e
echo $PLATFORM_RELATIONSHIPS | base64 -d | jq -r 'to_entries[] | select(.value[].scheme=="mysql") | ["[client]|", "host=",.value[].host, "|user=", .value[].username, "|password=\"", .value[].password,"\""] | @tsv' | tr -d '\t' | tr '|' '\n' > ~/.my.cnf
-
git commit
the changes and push them to your environment
Finally
Now, when running the mysql
you will automatically log you in to the database and no longer have to pass in the params.
If you are curious why that works, the .my.cnf gets written during the deploy hook, and gets read by the mysql
client. You can show the contents of it by running cat .my.cnf