Init Containers in Azure Container Apps : Database Initialization

  • Thread starter Thread starter Kinsuk
  • Start date Start date
K

Kinsuk

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.



949x536?v=v2.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



727x112?v=v2.png







Dockerfile for main app container







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







Output



653x191?v=v2.png

Continue reading...
 
Back
Top