Learn to work with Kubernetes Secrets by inspecting existing ones, creating a custom secret, and configuring a web application pod to use it.
In this lab, you’ll learn how to work with Kubernetes Secrets. We’ll start by inspecting the default Namespace’s secrets, then create a custom secret for database credentials and configure a web application pod to use it.
The application deployment follows a specific architecture where required pods and services are already running. Verify their current state by running:
Copy
Ask AI
kubectl get secrets
Copy
Ask AI
NAME TYPE DATA AGEdefault-token-cr4sr kubernetes.io/service-account-token 3 7m50s
Note that the default token secret is not used by the web application. It is instead intended to enable the web application to connect to the MySQL database.
The web application is failing to connect to the MySQL database. The error message is:
Copy
Ask AI
Environment Variables: DB_Host=Not Set; DB_Database=Not Set; DB_User=Not Set; DB_Password=Not Set; 2003: Can't connect to MySQL server on 'localhost:3306' (111 Connection refused)
This error indicates that the secret containing the database credentials has not been created. To resolve this, we need to create a new secret named “db-secret” with the necessary data fields.
Configuring the Web Application Pod to Use the New Secret
At present, the web application pod (webapp-pod) does not load the environment variables from the new “db-secret.” To pass these variables into the pod, update its configuration by referencing the secret.
For the existing web application pod, find the container section in its pod definition and add an entry under envFrom to reference db-secret. For example:
Using secrets to store sensitive data such as database credentials is a common practice. However, by default, these secrets are stored in etcd without encryption, potentially leaving them exposed to anyone with access to the Kubernetes API server or the etcd database.
For enhanced security, consider enabling encryption at rest and proper role-based access controls (RBAC) to protect your secrets.