In this guide we will show you how to connect two apps together in Kraftcloud; we
will use, as example, a web server written in Python as frontend and a MariaDB
instance as backend, as shown in this diagram:
If you haven’t come across what a service group is yet, you can have a glance at
this guide, but essentially in KraftCloud a
service group is the mechanism we use to expose apps to the Internet. So in this
guide we will attach the web server instance to the service group so that it’s
externally accessible, and then connect that instance to the MariaDB instance via
a private connection/IP.
Setting it Up
To start, let’s create the MariaDB instance (you can get more details about this in the MariaDB guide):
Note that we don’t specify the -p flag, since this instance will be private, i.e., it does not need
to connect to the Internet and so no service group is needed for it. We use the --name flag to tell
KraftCloud to set the instance’s name to mariadb, but more importantly, to use it as its private DNS name
so we can put that into our web server later. The resulting output of the deploy command should be similar to:
Note the private fqdn field’s value of mariadb.internal which will go into our Python server code.
Next we need to create the Python server to connect to the DB. We’ll use Flask for this:
Replace the contents of server.py and requirements.txt with:
With this in place, let’s start our Flask web server and create a service group for it via the -p flag:
You should see output similar to:
So now we have our Flask instance attached to a service group named quiet-river-w2muxbwe
and with public URL https://quiet-river-w2muxbwe.fra0.kraft.host.
Testing it
Simply curl the URL:
You should get results from the MariaDB database, i.e.,:
This is the result from the SELECT count(*) FROM user; query.