Jump to content

Init Containers in Azure Container Apps : Database Initialization

Featured Replies

Posted

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.

 

 

 

949x536vv2.png.941bfb676918821662f555512e68d797.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

 

 

 

727x112vv2.png.46b2f985a04d094bd0a42a604e46f339.png

 

 

 

 

 

 

 

Dockerfile for main app container

 

 

 

 

 

 

 

FROM python

COPY . .

RUN pip install mysql-connector && pip install flask

EXPOSE 5000

CMD ["python", "app.py"]

 

 

 

 

 

 

 

Output

 

 

 

653x191vv2.png.abb9dbc5ab039ef0ae7dc14b08b42d0d.png

 

Continue reading...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...