Feedback

Chat Icon

Cloud-Native Microservices With Kubernetes - 2nd Edition

A Comprehensive Guide to Building, Scaling, Deploying, Observing, and Managing Highly-Available Microservices in Kubernetes

23%

Deploying Stateful Microservices: Persisting Data in Kubernetes

The goal of this part is to demonstrate how to persist data in our application using a database. This will also be an opportunity to learn about more Kubernetes resources such as ConfigMap, PersistentVolume, PersistentVolumeClaim, and StorageClass. In the previous part, we created a Flask API that stored the to-do items in memory. Technically, even though it stored data in memory, we called it stateless-flask to indicate that the whole application did not use a database. We are now going to create a new Flask application that uses PostgreSQL as a database to store the to-do items and to persist the data.

When a user adds an item to the to-do list, it will not disappear when the Pod restarts, as everything will be saved to an external datastore. This will not make our microservice stateful, but rather a stateless microservice that stores its state in an external datastore. However, we will call our application stateful-flask to mark the difference from the previous application.

We don't need to install the required tools again if we followed the previous parts of this guide. However, if you are starting from scratch, make sure to follow these steps:

# Install pip
type -p pip3 >/dev/null || \
  (apt update && apt install -y python3-pip)

# Install virtualenvwrapper
pip3 show virtualenvwrapper >/dev/null || \
  pip3 install virtualenvwrapper

# Create a directory to store your virtual
# environments if it doesn't exist
export WORKON_HOME=~/Envs
[ -d "$WORKON_HOME" ] || mkdir -p $WORKON_HOME

# Add the configurations to .bashrc if they don't exist
grep -q "export WORKON_HOME=~/Envs" ~/.bashrc || \
  echo "export WORKON_HOME=~/Envs" >> ~/.bashrc

grep -q \
  "export VIRTUALENVWRAPPER_PYTHON='/usr/bin/python3'" ~/.bashrc || \
  echo "export VIRTUALENVWRAPPER_PYTHON='/usr/bin/python3'" \
  >> ~/.bashrc

grep -q "source /usr/local/bin/virtualenvwrapper.sh" ~/.bashrc || \
  echo "source /usr/local/bin/virtualenvwrapper.sh" >> ~/.bashrc

# Reload your shell
source ~/.bashrc

Cloud-Native Microservices With Kubernetes - 2nd Edition

A Comprehensive Guide to Building, Scaling, Deploying, Observing, and Managing Highly-Available Microservices in Kubernetes

Enroll now to unlock all content and receive all future updates for free.