Init Containers in Azure Container Apps : Database Initialization
Published Sep 20 2023 02:25 AM 3,285 Views
Microsoft

Suppose you're deploying a web application that relies on a database. Instead of manually configuring the database each time you deploy your application, you can use an Init Container to handle this task. The Init Container can run scripts to create tables, seed initial data, or set up the database schema. Once the database is ready, the main application container can safely start, knowing that the required database structure is in place.

 

The below example defines an init container which runs under the same pod as main app container, seeds data to an existing Azure MySQL Database which will be used by the main web app container to serve contents onto the landing page.

 

Kinsuk_0-1695106785349.png

 

The init container inserts a record into an existing table named myguests in Azure My SQL DB using a python script. The script contains code for connecting to the Database alongside inserting record into the Database. This data will then be retrieved and used by the main app container which is also running a python Flask based web application and return the value in the landing page.

 

Dockerfile for Init Container

 

 

 

FROM python
COPY . .
RUN pip install mysql && pip install mysql-connector-python
CMD ["python", "test.py"]

 

 

 

 

Python Script for Init Container

 

 

 

import mysql.connector

mydb = mysql.connector.connect(
  host="init-test.mysql.database.azure.com",
  user="*******",
  password="*******",
  database="*****"
)

mycursor = mydb.cursor()

sql = "INSERT INTO myguests (firstname, lastname, email) VALUES ('John', 'Doe', 'test@outlook.com')"

mycursor.execute(sql)

mydb.commit()

print(mycursor.rowcount, "record(s) affected")

 

 

 

 

Output from Init Container

 

Kinsuk_2-1695107664170.png

 

 

 

Dockerfile for main app container

 

 

 

FROM python
COPY . .
RUN pip install mysql-connector && pip install flask
EXPOSE 5000
CMD ["python", "app.py"]

 

 

 

Output

 

Kinsuk_3-1695107793080.png

 

 

Co-Authors
Version history
Last update:
‎Sep 19 2023 12:35 AM
Updated by: