Skip to content
ImagineWorld

SQL and NoSQL Databases at the Edge

node_idnode-book_edge-computing-systems-with-kubernetes_chapter-10-sql-and-nosql-databases-at-the-edge
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num10
chapter_titleSQL and NoSQL Databases at the Edge
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 10 — SQL and NoSQL Databases at the Edge

Section titled “Chapter 10 — SQL and NoSQL Databases at the Edge”

When you have to create an edge system, a critical task is storing your data. For this, you have to take into consideration the resources that you have, the processor that your devices are using, and the type of data that you want to store. CAP theorem states that distributed data stores only provide two of the following guarantees: consistency, availability, and partition tolerance. So, this theorem can help you to decide which type of database is best according to your system needs. In this chapter, we are going to learn how to deploy different database types to run on edge systems using K3s and ARM devices. These examples include different techniques such as using ConfigMaps and Secrets to deploy your databases.

In this chapter, we’re going to cover the following main topics:

  • CAP theorem for SQL and NoSQL databases
  • Creating a volume to persist your data
  • Using MySQL and MariaDB SQL databases
  • Using a Redis key-value NoSQL database
  • Using a MongoDB document-oriented NoSQL database
  • Using a PostgreSQL object-relational SQL database
  • Using a Neo4j graph NoSQL database

To deploy the databases in this chapter, you need the following:

  • A single- or multi-node K3s cluster using ARM devices with MetalLB, and Longhorn storage installed. If you are using Raspberry Pi devices, you will need at least 4 GB of RAM and at least the 4B model. Each node must have the Ubuntu ARM64 operating system in order to support the ARMv8 architecture, necessary for some deployments in this chapter.
  • kubectl configured to be used on your local machine, to avoid using the --kubeconfig parameter.
  • Clone the repository at https://github.com/PacktPublishing/Edge-Computing-Systems-with-Kubernetes/tree/main/ch10 if you want to run the YAML configuration by using kubectl apply instead of copying the code from the book. Take a look at the directory yaml for the YAML examples inside the ch10 directory.

With this, you can deploy the databases explained in this chapter. So, let’s get started learning about CAP theorem first, to choose the right database for your specific use case.

CAP theorem was defined by Eric Brewer in 1999 and presented at the 19th Annual ACM Symposium on Principles of Distributed Computing (PODC) in 2000. This theorem states that a distributed data store can only provide two of the following guarantees:

  • Consistency: This means when reading information, the data store returns the most recent written data or returns an error if it fails. This refers to regular SQL databases that use atomic operations to guarantee that data is written. If not, the system automatically rolls back to a previous data state.
  • Availability: This means that all reads contain data, but it might not be the most recent.
  • Partition tolerance: This is the most desired feature in a distributed system. It means that data is distributed in several nodes, helping to reduce downtime for the database. This means that if a node is down, just a small portion of data will be inaccessible:

Figure 10.1 – CAP theorem diagram

This theorem is commonly used as a point of reference to design strong distributed systems in the context of data. Now, in the CAP theorem diagram (Figure 10.1), represented as a triangle, you can see the different sides, and how each side has a relationship with the other sides. Let’s explore these sides and give examples of databases:

  • CA: On this side, we can classify databases that have consistency and availability. Here, we can find SQLite, which is a very simple database. MySQL and PostgreSQL are very popular open source databases. SQL Server is a proprietary database from Microsoft and Neo4j is a graph database. Each of these databases tries to guarantee consistency and availability. These guarantees can be found on relational database management system (RDBMS)-based databases. But as we have mentioned, Neo4j is classified on this side of the triangle. Something important on this side is that the database will fail if the network is down.
  • CP: On this side, you can find databases that provide consistency and partition tolerance. This means that databases such as Mongo and Redis use algorithms to write information that guarantee the consistency of data. For example, MongoDB uses the reader-writer algorithm to write in the database. Redis uses a similar algorithm to write data. Talking about partition tolerance, MongoDB can distribute information across nodes. This gives MongoDB the ability to partition the data. This is sharding, which provides the partition tolerance feature to MongoDB. Other databases based on Bigtable work similarly. Those Bigtable-based databases usually read data from distributed buckets of information across the cloud. The problem in CP is the risk that some data will become unavailable when a node or source of data is down.
  • AP: On this side, databases look for availability and partition tolerance. Here, we can find databases such as Cassandra, CouchDB, Riak, DynamoDB, and databases based on Cassandra. For example, Cassandra has high availability, using its masterless technique to scale servers, but it doesn’t guarantee the consistency of data. That’s a common issue in some NoSQL databases.

Before deciding which database is right for you, let’s explore what a relational and no-relational database is. A relational database is a database where the data is structured. This means that data is organized in tables, rows, and columns. These tables have relationships and dependencies. These databases use Structured Query Language (SQL) to manage the information. Relational databases are also called SQL databases. They also use ACID operations. This stands for atomicity, consistency, isolation, and durability; these properties in data guarantee data integrity when errors and failures happen. Some examples are MySQL, PostgreSQL, and SQL Server.

A non-relational database is not structured. It doesn’t use a table, row, and column data schema. Instead, it uses a storage model optimized for specific requirements of the type of data being stored. Some of these types of data could be JSON documents, key values, and so on. These databases are also called NoSQL databases. These databases don’t use ACID operations. They look for availability and partition tolerance for data. Some examples are MongoDB, Redis, Neo4j, and Cassandra. When choosing the right database, you can evaluate some of these questions:

  • Which of the guarantees of consistency, partition tolerance, and availability does my system need? According to this, which database fits my system needs best?
  • Does my database need to support the SQL language to query information?
  • Do I need a database that supports the SQL language?
  • Is my data not structured as JSON documents or do I need something structured as tables?
  • What type of data am I storing? Do I need a SQL or NoSQL database?
  • Do I need consistency, availability, or partition tolerance? Which of these components is important for my system?
  • How many resources is my database going to use? How many simultaneous connections is my system expected to handle?
  • Do I need to replicate information, implement rate limits, or have any other specific features in my database?
  • How fast is my database at writing and reading data?
  • How can I do replication or scaling on my database?

These and other questions could be important when choosing the right database. So, this chapter focuses on giving you a quick start when choosing the right database, using CAP theorem and some examples of how to deploy some SQL and NoSQL databases mentioned in the CAP theorem description. These SQL and NoSQL databases will be deployed at the edge in a K3s cluster using containers.

Important Note

You can find in the Further reading section some links to learn more about SQL and NoSQL databases, the official web links for the databases explained in this chapter, and complementary links to evaluate which database is best for your use case. A complementary theorem that you can use is the PACELC theorem. This looks for the trade-offs between latency and consistency when data is replicated.

Now let’s move on to create a volume to persist your data before performing the deployment of your selected database.

Before we start deploying our databases, let’s create a volume to store data first. For this, we have two options. One is to use a directory inside the server. This means that in order to not lose data, your Pods have to be provisioned in the same node as where your volume was created the first time. If you don’t want to depend on which node your pods are running, you have to choose a second option, which is to use a storage driver. If that’s your case, we are going to use Longhorn as our storage driver option. Now, let’s create our storage first, using a local directory. For this, follow the next steps:

  1. Create a PersistentVolume using the /mnt/data directory in the node to store data:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: PersistentVolume
    metadata:
    name: db-pv-volume
    labels:
    type: local
    spec:
    storageClassName: manual
    capacity:
    storage: 5Gi
    accessModes:
    - ReadWriteOnce
    hostPath:
    path: "/mnt/data"
    EOF
  2. Create a PersistentVolumeClaim using 5 GB of storage:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: PersistentVolumeClaim
    metadata:
    name: db-pv-claim
    spec:
    storageClassName: manual
    accessModes:
    - ReadWriteOnce
    resources:
    requests:
    storage: 5Gi
    EOF

If you want to use Longhorn as your storage, follow the next steps:

  1. Create a PersistentVolumeClaim with 5 GB of storage, this time, using Longhorn:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: PersistentVolumeClaim
    metadata:
    name: db-pv-claim
    spec:
    accessModes:
    - ReadWriteOnce
    storageClassName: longhorn
    resources:
    requests:
    storage: 5Gi
    EOF

This is a critical step to persist and avoid losing your data. In the next sections, we are going to start deploying our databases, starting with basic configuration and adding more complex configurations such as using ConfigMaps and Secrets to perform more production-ready deployments. But first, let’s start with MySQL and MariaDB, very popular databases used across the internet.

MySQL is a relational database that uses the SQL language to read and write information. It’s one of the most used databases on the internet. MariaDB is a fork of MySQL and the version used in this example is fully compatible with MySQL. It’s a very fast SQL database and it’s simple to use. After this brief introduction to MySQL, let’s get started deploying this database by following the next steps:

  1. Create the MySQL deployment creating a PersistentVolumeClaim called db-pv-claim:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: apps/v1
    kind: Deployment
    metadata:
    name: mysql
    spec:
    selector:
    matchLabels:
    app: mysql
    strategy:
    type: Recreate
    template:
    metadata:
    labels:
    app: mysql
    spec:
    containers:
    - image: mysql:8.0.28-oracle
    name: mysql
    env:
    - name: MYSQL_ROOT_PASSWORD
    value: password
    ports:
    - containerPort: 3306
    name: mysql
    volumeMounts:
    - name: mysql-persistent-storage
    mountPath: /var/lib/mysql
    volumes:
    - name: mysql-persistent-storage
    persistentVolumeClaim:
    claimName: db-pv-claim
    EOF

Important Note

Instead of using MySQL, you can use MariaDB, which is fully compatible with MySQL version 5.6. To do this, change the mysql:8.0.28-oracle image to arm64v8/mariadb:latest and the MYSQL_ROOT_PASSWORD variable to MARIADB_ROOT_PASSWORD. You can also check for other image versions in https://hub.docker.com for MySQL and MariaDB images. For this deployment, the password is password. The images used for the deployment are both designed to run on ARM devices. In the case of MySQL reinstallation using local storage, you have to delete the content inside the /mnt/data directory using the rm -R /mnt/data command to avoid errors.

  1. Now let’s create our service to access MySQL using a service:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: Service
    metadata:
    name: mysql
    spec:
    ports:
    - port: 3306
    selector:
    app: mysql
    clusterIP: None
    EOF
  2. To test whether your MySQL deployment works, you can access your deployment pod by running this:
    $ kubectl exec -it $(kubectl get pods -l app=mysql --output=jsonpath={..metadata.name}) -- bash

Inside the pod, run the following command to connect to your database:

$ mysql -h localhost -uroot -ppassword

Now, the prompt will change to mysql>. Let’s create a simple database, EXAMPLE, with the VALUE_TABLE table, and insert and list some records. To do this, run the following commands and you will see output like this:

mysql> CREATE DATABASE EXAMPLE;
Query OK, 1 row affected (0.02 sec)
mysql> USE EXAMPLE;
Database changed
mysql> CREATE TABLE VALUE_TABLE (ID INT PRIMARY KEY NOT NULL,VALUE INT NOT NULL);
Query OK, 0 rows affected (0.10 sec)
mysql> INSERT INTO VALUE_TABLE (ID,VALUE) VALUES (1,123);
Query OK, 1 row affected (0.03 sec)
mysql> SELECT * FROM VALUE_TABLE;
+----+-------+
| ID | VALUE |
+----+-------+
| 1 | 123 |
+----+-------+
1 row in set (0.00 sec)
  1. Finally, delete the table and database with the following commands:
    mysql> DROP TABLE VALUE_TABLE;
    Query OK, 0 rows affected (0.07 sec)
    mysql> DROP DATABASE EXAMPLE;
    Query OK, 0 rows affected (0.05 sec)
    mysql> EXIT
    Bye

Now you have learned how to use MySQL with this basic deployment and example. Now let’s move on to learn how Redis works.

Now it’s time to use Redis as our key-value database. Redis is a nice key-value database that doesn’t consume many resources. All its data is stored in memory. It has very interesting types of data such as hash keys, lists, and sets. It also implements publisher-subscriber and streaming features to implement channels of communication and simple broker functionalities. For our Redis deployment, we are going to use a custom configuration to set the password for Redis, and a storage volume to prevent losing data. To use Redis in your cluster, follow the next steps:

  1. Create the ConfigMap to use a custom configuration with the password K3s123- and the /data directory to store Redis data:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: ConfigMap
    metadata:
    name: redis-configmap
    data:
    redis-config: |
    dir /data
    requirepass YOUR_PASSWORD
    EOF
  2. Create the deployment for Redis using the previous ConfigMap called redis-configmap and mounted as the redis.conf file. We also use the PersistentVolumeClaim called db-pv-claim, and some resource limits for the deployment, setting the CPU and memory. Let’s create the deployment by running the following command:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: apps/v1
    kind: Deployment
    metadata:
    labels:
    run: redis
    name: redis
    spec:
    replicas: 1
    selector:
    matchLabels:
    run: redis
    template:
    metadata:
    labels:
    run: redis
    spec:
    containers:
    - name: redis
    image: arm64v8/redis:6.2
    command:
    - redis-server
    - /redisconf/redis.conf
    ports:
    - containerPort: 6379
    resources:
    limits:
    cpu: "0.2"
    memory: "128Mi"
    volumeMounts:
    - mountPath: "/data"
    name: redis-storage
    - mountPath: /redisconf
    name: config
    volumes:
    - name: config
    configMap:
    name: redis-configmap
    items:
    - key: redis-config
    path: redis.conf
    - name: redis-storage
    persistentVolumeClaim:
    claimName: db-pv-claim
    EOF
  3. Now create the redis, which points to port 6379 in our redis deployment:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: Service
    metadata:
    labels:
    run: redis
    name: redis
    spec:
    ports:
    - port: 6379
    protocol: TCP
    targetPort: 6379
    selector:
    run: redis
    type: ClusterIP
    EOF

This service creates a DNS record inside the cluster called redis that points to our redis deployment. This DNS record is accessible to other deployments in the cluster.

  1. Let’s access our Redis pods to test some basic commands to store a value in our database. To do this, run the following command:
    $ kubectl exec -it $(kubectl get pods -l run=redis --output=jsonpath={..metadata.name}) -- redis-cli

The prompt will look like this: 127.0.0.1:6379>.

  1. Now, authenticate to the Redis database using the AUTH command, and then use set and get to create the a key with the value 1. Finally, exit using the exit command. This simple test will look like this:
    127.0.0.1:6379> AUTH YOUR_PASSWORD
    OK
    127.0.0.1:6379> set a 1
    OK
    127.0.0.1:6379> get a
    "1"
    127.0.0.1:6379> exit

With this, you stored the a key with the value 1. Now you have used Redis to store simple values. After running exit, you will exit to the Redis pod.

Now you have learned how to deploy a simple Redis deployment, it’s time to deploy MongoDB in the next section.

Using a MongoDB document-oriented NoSQL database

Section titled “Using a MongoDB document-oriented NoSQL database”

MongoDB is a document-oriented NoSQL database. It stores its data as JSON documents. It also implements sharding techniques to distribute data across its nodes and uses the MapReduce technique for data aggregation. It’s easy to use and uses low resources for single node scenarios. For our MongoDB deployment, we are going to use a ConfigMap to store custom configurations. In this case, our MongoDB configuration is set to expose its port across the network, but for the moment we are not using Secrets to simplify the deployment. In the Using a PostgreSQL object-relational and SQL database section, we are going to explore the use of secrets, but before that, let’s follow the next steps to deploy MongoDB:

  1. Deploy your custom configuration to enable clients to connect to MongoDB:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: ConfigMap
    metadata:
    name: mongo-configmap
    data:
    mongod-conf: |
    dbpath=/var/lib/mongodb
    logpath=/var/log/mongodb/mongodb.log
    logappend=true
    bind_ip = 0.0.0.0
    port = 27017
    journal=true
    auth = true
    EOF

This exposes MongoDB to listen on port 27017 across the network.

  1. Create the deployment using the ConfigMap called mongo-configmap, the PersistentVolumeClaim, and the MONGO_INITDB_ROOT_USERNAME, MONGO_INITDB_ROOT_PASSWORD, and MONGO_INITDB_DATABASE variables, which set the initial root, user, and the password to connect to MongoDB as root or with your defined user:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: apps/v1
    kind: Deployment
    metadata:
    labels:
    app: mongo
    name: mongo
    spec:
    replicas: 1
    selector:
    matchLabels:
    app: mongo
    template:
    metadata:
    labels:
    app: mongo
    spec:
    containers:
    - image: arm64v8/mongo:4.4
    name: mongo
    env:
    - name: MONGO_INITDB_ROOT_USERNAME
    value: "admin"
    - name: MONGO_INITDB_ROOT_PASSWORD
    value: "YOUR_PASSWORD"
    - name: MONGO_INITDB_DATABASE
    value: "mydatabase"
    ports:
    - containerPort: 27017
    resources:
    limits:
    cpu: "0.5"
    memory: "200Mi"
    volumeMounts:
    - mountPath: "/data/db"
    name: mongo-storage
    - mountPath: /mongoconf
    name: config
    volumes:
    - name: config
    configMap:
    name: mongo-configmap
    items:
    - key: mongod-conf
    path: mongod.conf
    - name: mongo-storage
    persistentVolumeClaim:
    claimName: db-pv-claim
    EOF

Important Note

Be aware that if you want to use a version of MongoDB greater than 5.0, you need a device with ARMv8.2-A or higher in order to use it. That’s the reason to use MongoDB 4.4 for this example. MongoDB 4.4 is supported to run on ARMv8 processors such as a Raspberry Pi.

  1. Now create the service that exposes your MongoDB deployment as a service accessible inside the cluster (MongoDB uses port 27017 to connect):
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: Service
    metadata:
    labels:
    app: mongo
    name: mongo
    spec:
    ports:
    - port: 27017
    protocol: TCP
    targetPort: 27017
    selector:
    app: mongo
    type: ClusterIP
    EOF
  2. Access the pod that contains MongoDB to test whether you are able to write some data:
    $ kubectl exec -it $(kubectl get pods -l app=mongo --output=jsonpath={..metadata.name}) -- mongo -uadmin -pYOUR_PASSWORD

Once you are inside the pod, change into mydatabase and insert the {"a":1} document in the mycollection collection using db.mycolletion.insert. Then, list the inserted document using db.mycollection.find. Finally, execute exit to finish the Mongo session. The commands and output of this execution will look like this:

> use mydatabase
switched to db mydatabase
> db.mycollection.insert({"a":1})
WriteResult({ "nInserted" : 1 })
> db.mycollection.find()
{ "_id" : ObjectId("622c498199789d3b03b20c45"), "a" : 1 }
> exit
Bye

These are some basic commands to use MongoDB, to have a quick start with Mongo.

Now you know how to deploy a simple MongoDB database in K3s, let’s move on to learn how to use Postgres in the next section.

Using a PostgreSQL object-relational and SQL database

Section titled “Using a PostgreSQL object-relational and SQL database”

PostgreSQL is an object-relational database, used because of its strong reputation for reliability, feature robustness, and performance. It uses SQL to query its data. It’s also commonly used for storing files or to store data used to create machine learning models. So, let’s learn how to deploy PostgreSQL in a very simple way. To do this, follow the next steps:

  1. For this example, let’s use Kubernetes Secrets, and let’s create the password as YOUR_PASSWORD to give an example of how to hide sensible information as passwords. For this, let’s generate a Base64 encoding for your password with the following command:
    $ echo "YOUR_PASSWORD"| tr -d "\n" | base64

The output will look like this:

WU9VUl9QQVNTV09SRA==
  1. Use the previous output to create your Secret object using a YAML file. You can create the db-password Secret with this value using the following command:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: Secret
    metadata:
    name: db-password
    data:
    password: WU9VUl9QQVNTV09SRA==
    EOF
  2. Now create the Postgres deployment with the following command:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: apps/v1
    kind: Deployment
    metadata:
    labels:
    app: postgres
    name: postgres
    spec:
    replicas: 1
    selector:
    matchLabels:
    app: postgres
    template:
    metadata:
    labels:
    app: postgres
    spec:
    containers:
    - image: arm64v8/postgres:14.2
    name: postgres
    env:
    - name: PGDATA
    value: "/var/lib/postgresql/data/pgdata"
    - name: POSTGRES_PASSWORD
    valueFrom:
    secretKeyRef:
    name: db-password
    key: password
    ports:
    - containerPort: 5432
    resources:
    limits:
    cpu: "0.5"
    memory: "200Mi"
    volumeMounts:
    - mountPath: "/var/lib/postgresql/data"
    name: postgres-storage
    volumes:
    - name: postgres-storage
    persistentVolumeClaim:
    claimName: db-pv-claim
    EOF
  3. Now create the postgres service by running the following command:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: Service
    metadata:
    labels:
    app: postgres
    name: postgres
    spec:
    ports:
    - port: 5432
    protocol: TCP
    targetPort: 5432
    selector:
    app: postgres
    type: ClusterIP
    EOF
  4. Access the pod that contains Postgres to test whether you can write some data. To do this, run the following command:
    $ kubectl exec -it $(kubectl get pods -l app=postgres --output=jsonpath={..metadata.name}) -- bash -c "PGPASSWORD='YOUR_PASSWORD' psql -h postgres -U postgres"
  5. The prompt will look like postgres=#. Next, you will find some example commands and their output. This commands will be used to test whether our database works.

First, create the VALUE_TABLE table with the ID and VALUE fields:

postgres=# CREATE TABLE VALUE_TABLE (ID INT PRIMARY KEY NOT NULL,VALUE INT NOT NULL);
CREATE TABLE

Then insert a record with ID = 1 and VALUE = 123:

postgres=# INSERT INTO VALUE_TABLE (ID,VALUE) VALUES (1,123);
INSERT 0 1

Show the values:

postgres=# SELECT * FROM VALUE_TABLE;
id | value
----+-------
1 | 123
(1 row)

Delete the table:

postgres=# DROP TABLE VALUE_TABLE;
DROP TABLE

Exit from Postgres:

postgres=# exit

Now you’ve learned how to install and run basic commands with Postgres to store your data in this database, let’s move on to learn about Neo4j, a graph NoSQL database, in the next section.

Neo4j is a graph database that can be used to store relationships between objects. Neo4j uses Cypher Query Language (CQL), which is the equivalent of SQL for relational databases. Neo4j also represents data using nodes, relationships, properties, and labels in a visual way. It supports ACID operations and native graph storage and processing. It has great scalability and enterprise support. Because of the way it stores data, it can be used for IoT applications to query relationships between data. So now, let’s install Neo4j by following the next steps:

  1. Create the deployment for Neo4j:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: apps/v1
    kind: Deployment
    metadata:
    labels:
    app: neo4j
    name: neo4j
    spec:
    replicas: 1
    selector:
    matchLabels:
    app: neo4j
    template:
    metadata:
    labels:
    app: neo4j
    spec:
    containers:
    - image: arm64v8/neo4j
    name: neo4j
    env:
    - name: NEO4J_AUTH
    value: none
    ports:
    - containerPort: 7474
    name: http
    - containerPort: 7687
    name: bolt
    - containerPort: 7473
    name: https
    volumeMounts:
    - name: neo4j-data
    mountPath: "/var/lib/neo4j/data"
    volumes:
    - name: neo4j-data
    persistentVolumeClaim:
    claimName: db-pv-claim
    EOF

In this deployment, we are using the NEO4J_AUTH variable with its value set to none, to use the non-authentication method, just to simplify this example. You can also explore how to use secrets and other options by modifying this configuration.

Important Note

If you delete the NEO4J_AUTH variable, Neo4j by default sets the user name and password to neo4j. Then, after logging in, a dialog box will ask you to change this password.

  1. Create the service to expose the bolt, http, and https ports that Neo4j uses:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: Service
    metadata:
    labels:
    app: neo4j
    name: neo4j
    spec:
    ports:
    - name: https
    port: 7473
    protocol: TCP
    targetPort: 7473
    - name: http
    port: 7474
    protocol: TCP
    targetPort: 7474
    - name: bolt
    port: 7687
    protocol: TCP
    targetPort: 7687
    selector:
    app: neo4j
    type: ClusterIP
    EOF
  2. Expose the http and bolt ports, before connecting to Neo4j with the browser. To do this, run the following commands in different terminals:
    $ kubectl port-forward service/neo4j 7474:7474
    $ kubectl port-forward service/neo4j 7687:7687
  3. Open your browser at the page http://localhost:7474, choose Authentication type: No authentication, then click on the Connect button:

Figure 10.2 – Neo4j login page

Then you will see the Neo4j UI:

Figure 10.3 – Neo4j main page

  1. Run a simple example in the Neo4j terminal located at the top of the browser as neo4j$. To do this, add the next commands and run them by clicking on the blue triangle button:
    CREATE (IronMan:Hero{name: "Tony Stark"})
    CREATE (Thanos:Villainous {name: "Thanos"})
    CREATE (Thanos)-[r:ENEMY_OF]->(IronMan)
    RETURN IronMan, Thanos

You will see that Neo4j visualizes the relationship between the Marvel characters:

Figure 10.4 – Neo4j graph visualization

Now you have learned how to use Neo4j with this basic example, let’s move on to the summary of this chapter, about what we have learned.

In this chapter, we learned how to use CAP theorem to choose the right database to store data. This theorem helped us to take into consideration important guarantees when designing distributed data storage in a distributed system at the edge. In this chapter, we also learned about different relational and non-relational databases. We gained practical knowledge on how to set up and deploy various database paradigms such as relational, key-value, document-oriented, and graph databases. In the next chapter, we are going to focus on the time series database Prometheus, which stores data in the form of values and time and can be used to implement useful monitoring dashboards for devices at the edge.

Here are a few questions to validate your new knowledge:

  • How can CAP theorem help you to decide which database to use according to your use case?
  • How can you deploy MySQL in K3s?
  • How can you deploy Redis in K3s?
  • How can you deploy MongoDB in K3s?
  • How can you deploy PostgreSQL on K3s?
  • How can you deploy Neo4j on K3s?
  • How can you use PersistentVolumeClaims to deploy a database on K3s?
  • How can you use ConfigMaps and Secrets to deploy a database on K3s?

You can refer to the following references for more information on the topics covered in this chapter: