Deploy LAMP on rocky Linux using Vagrant

#Introduction

In this tutorial, How to deploy LAMP on Rocky Linux using Vagrant. LAMP is Linux Operating System, Apache Web Server, MySQL Database, and PHP Programming Language.

Development Environments Made Easy Quote by www.vagrantup.com

My Environment

  • Host OS: Window 11 or Ubuntu / Centos or Rocky server.
  • Vagrant version: 2.2.18
  • Vagrant provider: VirtualBox
  • Boxes Vagrant: rockylinux/8
  • Terminal/PowerShell

Deploy LAMP on rocky Linux using Vagrant directory and files will look like as below:

C:\MYDATA\VAGRANT_VMS\PROJECTS\VAGRANT\ROCKY-LAMP
|   Vagrantfile
|
+---Files
|       gitconfig
|       index.html
|       info.php
|
\---Scripts
        lamp-rocky.sh

Create a Virtual Machine

Navigate to my working directory and create an initial Vagrantfile if one does not already exist.

cd Rocky-LAMP
vagrant init rockylinux/8

Configure the Virtual Machine

You need to edit the Vagrantfile and paste the content as below

# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|

  config.vm.box = "rockylinux/8"
  config.vm.hostname = "devopsroles.com"
  config.ssh.insert_key = false
  config.vm.network "private_network", ip: "192.168.4.4"
  config.vm.network "forwarded_port", guest: 80, host: 8888
  config.vbguest.auto_update = false
  # Install LAMP on Rocky server
  config.vm.provision "shell", 
  path: "C:\\MyData\\Vagrant_VMS\\Projects\\Vagrant\\Rocky-LAMP\\Scripts\\lamp-rocky.sh"
  # Test HTML
  #config.vm.provision "file", 
  # source: "C:\\MyData\\Vagrant_VMS\\Projects\\Vagrant\\Rocky-LAMP\\Files\\index.html",
  # destination: "/var/www/html/index.html"
  #Test PHP
  #config.vm.provision "file", 
  # source: "C:\\MyData\\Vagrant_VMS\\Projects\\Vagrant\\Rocky-LAMP\\Files\\info.php",
  # destination: "/var/www/html/info.php"
end

I use provision shell to install Apache, MySQL, and PHP on Rocky Linux. The script update OS, install the packages: Apache PHP and MySQL.

The content “lamp-rocky.sh” script is as below:

#!/bin/bash

#Update OS
sudo yum update -y --exclude=kernel

#Tools
sudo yum install -y git unzip

#Apache
sudo dnf install -y httpd httpd-devel httpd-tools

#chkconfig --add httpd
sudo systemctl enable httpd.service
sudo systemctl stop httpd

sudo systemctl start httpd

#PHP
sudo dnf install -y php php-cli php-gd php-curl php-zip php-mbstring php-opcache php-intl php-mysqlnd

#MySQL
sudo yum install -y mysql mysql-server mysql-devel
sudo systemctl enable mysqld.service
sudo systemctl start mysqld

mysql -u root -e "SHOW DATABASES";

# content
sudo rm -rf /var/www/html/*
sudo cp -rf /vagrant/Files/{index.html,info.php} /var/www/html/
# cd /vagrant
#sudo -u vagrant wget -q https://raw.git.....

sudo systemctl restart httpd

Deploy LAMP on Rocky Linux

We use the “vagrant up” command line. This command creates and configures guest machines according to your Vagrantfile

vagrant up

How to connect to the virtual machine.

vagrant ssh

The output terminal as below

C:\MyData\Vagrant_VMS\Projects\Vagrant\Rocky-LAMP>vagrant ssh
[vagrant@devopsroles ~]$ cat /etc/redhat-release
Rocky Linux release 8.5 (Green Obsidian)
[vagrant@devopsroles ~]$ ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 08:00:27:fc:e9:96 brd ff:ff:ff:ff:ff:ff
    inet 10.0.2.15/24 brd 10.0.2.255 scope global dynamic noprefixroute eth0
       valid_lft 85565sec preferred_lft 85565sec
    inet6 fe80::a00:27ff:fefc:e996/64 scope link
       valid_lft forever preferred_lft forever
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 08:00:27:cf:7f:96 brd ff:ff:ff:ff:ff:ff
    inet 192.168.4.4/24 brd 192.168.4.255 scope global noprefixroute eth1
       valid_lft forever preferred_lft forever
    inet6 fe80::a00:27ff:fecf:7f96/64 scope link
       valid_lft forever preferred_lft forever

You need to open a browser that can access your Server’s IP address.

The resulting output picture as below:

A page displaying the PHP version among other parameters such as details of PHP extensions enabled will be displayed below

Conclusion

You have to deploy LAMP on rocky Linux using Vagrant. I hope will this your helpful. Thank you for reading the DevopsRoles page!

vagrant ssh Permission denied fixed: A Comprehensive Guide

Introduction

In this tutorial, How to fix vagrant SSH permission denied. I use Host OS Windows 11 and Vagrant. I have to deploy a VM using Vagrant. Finish, login ssh to guest OS.

vagrant up command error as below:

vagrant@127.0.0.1: Permission denied (publickey,gssapi-keyex,gssapi-with-mic)

Understanding the Error

What is the “vagrant ssh Permission denied” Error?

The “vagrant SSH Permission denied” error occurs when the Vagrant fails to establish an SSH connection to the virtual machine. This can be caused by various issues such as incorrect SSH keys, misconfigured Vagrantfiles, or permission issues.

Common Causes

  1. Incorrect SSH Key Permissions: The SSH key file might not have the correct permissions.
  2. Missing or Incorrect SSH Keys: The SSH key might be missing or not properly configured.
  3. Vagrantfile Misconfiguration: The Vagrantfile may have incorrect settings.
  4. User Permissions: The user running Vagrant may not have the necessary permissions.

My Environment

  • Host OS: Windows 11 or Linux/Ubuntu/Redhat
  • Vagrant version: 2.2.18
  • Vagrant provider: VirtualBox
  • Boxes Vagrant: rockylinux/8

For example, My Vagrantfile

# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|

  config.vm.box = "rockylinux/8"
  config.vm.network "forwarded_port", guest: 80, host: 8888
  config.vbguest.auto_update = false
end

Deploy a Virtual Machine

vagrant up

The output terminal is as follows:

How do fix vagrant SSH permission denied

I add configure “config.ssh.insert_key = false” into the Vagrantfile file

After changing my Vagrantfile as the content below

# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|

  config.vm.box = "rockylinux/8"
  config.ssh.insert_key = false
  config.vm.network "forwarded_port", guest: 80, host: 8888
  config.vbguest.auto_update = false
end

The result

Frequently Asked Questions

Why am I getting a “vagrant SSH permission denied” error?

This error occurs when Vagrant fails to establish an SSH connection to the virtual machine, often due to incorrect SSH key permissions, missing keys, misconfigured Vagrantfiles, or user permission issues.

How do I fix SSH key permission issues in Vagrant?

You can fix SSH key permission issues by setting the correct permissions with the command chmod 600 ~/.ssh/id_rsa.

Can I regenerate the SSH key for Vagrant?

Yes, you can regenerate the SSH key for Vagrant by destroying the existing machine, removing the old key, and reinitializing Vagrant.

How do I manually add an SSH key to the SSH agent?

Start the SSH agent eval "$(ssh-agent -s)" and add your SSH key with ssh-add ~/.ssh/id_rsa.

Should I update Vagrant and its plugins?

Yes, updating Vagrant and its plugins can resolve many issues, including SSH connection problems. Use vagrant plugin update and vagrant box update to update them.

Conclusion

Encountering the “vagrant SSH Permission denied” error can be frustrating, but with the steps outlined in this guide, you should be able to resolve it efficiently. From checking SSH key permissions to updating Vagrant, these solutions cover both basic and advanced troubleshooting methods. Ensuring smooth operation of your Vagrant environments is crucial for a seamless development workflow. Thank you for reading the DevopsRoles page!

Install LAMP Stack on Rocky Linux

Introduction

In this tutorial, How to Install LAMP Stack on Rocky Linux. A LAMP stack, which stands for Linux, Apache, MySQL (or MariaDB), and PHP, is a popular software bundle that provides the necessary components for hosting dynamic websites and web applications. In this tutorial, we’ll walk you through the steps to set up a LAMP stack on a Rocky Linux server.

Prerequisites

Before we begin, ensure that you have:

  • A running Rocky Linux instance
  • Root or sudo privileges
  • A stable internet connection

How to install LAMP Stack on Rocky Linux

Install Apache on Rocky Linux

Apache HTTP Server is one of the most widely used web servers in the world. To install it, run the following command:

dnf install -y httpd httpd-devel httpd-tools

Enable Apache start at boot time

systemctl enable httpd

start the Apache HTTPd daemon

systemctl start httpd

To check Apache running on Rocky Linux

systemctl status httpd

The output terminal is below

Opens a browser that can access your Server’s IP address

http://Your-IP-address
OR
http://domain.com

Install MariaDB on Rocky Linux

Next, you’ll need a database server. You can choose between MariaDB and MySQL. In this example, we’ll use MariaDB. Install it with the following command:

dnf install mariadb-server mariadb

The output terminal as below

Enable MariaDB to start at boot time

systemctl enable --now mariadb

Start the MariaDB daemon

systemctl start mariadb

To check MariaDB running on Rocky Linux

systemctl status mariadb

Additional steps to harden the database server. Run the MariaDB security script to secure your installation:

mysql_secure_installation
Set root password? [Y/n] y
Remove anonymous users? [Y/n] y
Disallow root login remotely? [Y/n] y
Remove test database and access to it? [Y/n] y
Reload privilege tables now? [Y/n] y

Follow the on-screen prompts to set a root password and improve the security of your database server.

Install PHP on Rocky Linux

The default PHP stream is PHP 7.2. PHP is a server-side scripting language commonly used in web development. Install PHP and the PHP MySQL extension with the following command:

To install the latest module Stream. We will reset the PHP streams.

dnf module reset php

Install PHP 7.4

dnf module install php:7.4

The output terminal is below

Install additional PHP extensions

dnf install php-cli php-gd php-curl php-zip php-mbstring php-opcache php-intl php-mysqlnd

Confirm the version of PHP installed

php -v

The output terminal is below

Test Your Install LAMP Stack

To verify that your LAMP stack is installed and running correctly, create a test PHP file in the Apache web root directory. We’ll use info.php as an example:

We create a test PHP file in the /var/www/html path.

vi /var/www/html/info.php

The content info.php is below

<?php
phpinfo();
?>

Save the changes and restart the webserver.

systemctl restart httpd

Open back browser

http://server-ip/info.php

The output is below

Remove file test PHP

rm -f /var/www/html/info.php

Conclusion

Congratulations! You’ve successfully install LAMP stack on your Rocky Linux server. You now have a powerful platform for hosting websites and web applications. Remember to secure your server, keep your software up to date, and regularly back up your data to ensure a stable and reliable web hosting environment. I hope will this your helpful. Thank you for reading the DevopsRoles page!

This comprehensive guide should equip you with the knowledge to manage and expand your LAMP stack setup. For any further customization or troubleshooting, refer to the official documentation and community forums. Happy coding!

Refer to:

Vagrant: Unknown configuration section vbguest

#Introduction

In this tutorial, How to fix the Unknown configuration section vbguest on Vagrant. Now, let’s fix Vagrant: Unknown configuration section vbguest.

  • Environment: CentOS 6x.
  • Vagrant version 2.2.18

My Vagrantfile

Vagrant.configure("2") do |config|
-----
config.vbguest.auto_update = false
-----

Error: Unknown configuration section vbguest

The reason is because of the missing vagrant.vbguest plugin.

Check plugin for Vagrant

C:\Users\HuuPV>vagrant plugin list
not found

1.If not, install “vagrant-vbguest

C:\MyData\Vagrant_VMS\Projects\Vagrant\Centos6.5-LAMP>vagrant plugin install vagrant-vbguest
Installing the 'vagrant-vbguest' plugin. This can take a few minutes...
Fetching micromachine-3.0.0.gem
Fetching vagrant-vbguest-0.30.0.gem
Installed the plugin 'vagrant-vbguest (0.30.0)'!

2. If exist, uninstall and reinstall “vagrant-vbguest

vagrant plugin uninstall vagrant-vbguest
vagrant plugin install vagrant-vbguest

Conclusion

You have fixed Vagrant: Unknown configuration section vbguest. I hope will this your helpful. Thank you for reading the DevopsRoles page!

Git Cheat Sheet

Introduction

How to use the git command every day. Git Cheat Sheet I use it every day. Git has become an essential tool for developers, allowing them to efficiently manage version control and collaborate on projects.

this guide will provide you with a comprehensive overview of Git’s essential commands and workflow. Let’s dive in!

What does Git mean?

Git is software for tracking changes in any set of files, usually used for coordinating work among programmers collaboratively developing source code during software development. Quote from Wikipedia.

Git Cheat Sheet Example

Check my git configure

git config -l

Configuration

Before you start using Git, it’s crucial to set up your configuration. You can configure your username and email globally using the git config command. For example Setup my Git username and Email Id

git config --global user.name "HuuPV"
git config --global user.email "HuuPV@devopsroles.com"

Username and EmailID assigned to commit from local computer.

Creating and Cloning Repositories

git init

Add a file to the staging area in Git

git add file_name

Add all files in your project to the staging area in Git

git add .

Commit changes for the files in a local repo.

git commit
git commit -m "first commit"

Shows the commit history for the current repository

git log

Show if a file is in the staging area, but not committed

git status

Remove tracked files from the current working tree

git rm filename

Rename files

git mv oldfile newfile

Branches

Branches are a powerful feature in Git, allowing you to work on different versions of your code simultaneously.

Create a new branch

git branch branch_name

Switch to a newly created branch

git checkout branch_name

Create a new branch and switch it immediately

git checkout -b branch_name

List branches

git branch

Merge and Remote Repositories

Merge two branches

git merge branch_name

Add a remote repository to your local repository

git add remote https://repo_url_here

Git clone

git clone

download updates from a remote repository.

git pull

After committing your changes, the next you send changes to the remote server.

git push
#or force push
git push -f

History and Logs

Git provides extensive tools to explore commit history. The git log the command shows the commit history

git log

The display presents a more compact view

git log --oneline

If you prefer a graphical representation, git log --graph creates a commit history graph.

git log --graph

To view the details of a specific commit

git show <commit>

Conclusion

Git is a powerful version control system that enables efficient collaboration and project management. This guide has provided an overview of essential Git commands and workflows, giving you a solid foundation to start using Git effectively

You have used Git Cheat Sheet every day. I hope will this your helpful. Thank you for reading the DevopsRoles page!

Backup and restore a Postgres database

Introduction

In this tutorial, How to backup and restore a Postgres database. You have installed the PostgreSQL database system.

Why Backup Your PostgreSQL Database?

Before we dive into the how, let’s briefly discuss the importance of regular database backups:

  • Data Loss Prevention: Backups protect your data against accidental deletion, corruption, or hardware failures.
  • Disaster Recovery: In the event of a catastrophic failure or data breach, having a backup allows you to quickly recover and restore your database.
  • Testing and Development: Backups can be used to create copies of your database for testing, development, or staging purposes.

Now, let’s get started with the backup and restore process.

Backup and restore a Postgres database

Backup a PostgreSQL Database

The pg_dump command is the PostgreSQL utility for creating database backups. Here’s the basic syntax:

pg_dump -U your_postgres_user -d your_database_name -f backup_file.sql

For example: import and export my-db database as below

The output format is a plain-text SQL script file ( The default)

root@5cc6d8f56baf:/# pg_dump -h localhost -U devopsroles my-db > my-db.sql

You can compress this data by using the “custom” dump format:

# format tar
root@5cc6d8f56baf:/# pg_dump -h localhost -U devopsroles -F t my-db > my-db.tar

Backup use pg_dump via a compression tool such as gzip

root@5cc6d8f56baf:/# pg_dump -h localhost -U devopsroles my-db | gzip > my-db.gz

Backup Remote PostgreSQL Databases

pg_dump -U devopsroles -h 192.168.1.122 -p 5432 my-db > my-db.sql

To explain:

  • -U: to specify the database role name
  • -h: remote host
  • -p: port a PostgreSQL database

To back up all PostgreSQL databases

root@5cc6d8f56baf:/# pg_dumpall -h localhost -U devopsroles > all_pg_dbs.sql

Restore the dump using the psql command

pgsql -f all_pg_dbs.sql postgres

Restoring a PostgreSQL Database

You can use psql or pg_restore utilities for retore postgres databases.

For example:

root@5cc6d8f56baf:/# psql -h localhost -U devopsroles my-db < my-db.sql
root@5cc6d8f56baf:/# pg_restore -h localhost -U devopsroles -d my-db my-db.tar

Conclusion

egularly backing up and, if necessary, restoring your PostgreSQL database is essential for data protection and disaster recovery. Remember to schedule automated backups, keep your backup files in a secure location, and test your backup and restore procedures periodically to ensure they work as expected.

By following these steps, you can safeguard your data and have peace of mind knowing that your PostgreSQL database is protected against data loss and system failures.

You have Backup and restore a Postgres database. I hope will this your helpful. Thank you for reading the DevopsRoles page!

Docker run PostgreSQL: A Step-by-Step Guide

Introduction

In today’s fast-paced development environments, the ability to quickly deploy and manage databases is crucial. Docker provides a powerful solution for running PostgreSQL databases in isolated containers, making it easier to develop, test, and deploy your applications. In this tutorial, you will learn how to use Docker run PostgreSQL databases and connect to them, enabling you to efficiently manage your database environments with minimal setup. Whether you’re new to Docker or looking to streamline your database management, this guide will equip you with the essential knowledge to get started.

  • PostgreSQL is a powerful, open-source object-relational database
  • Docker is an open platform that runs an application in an isolated environment called a container.

Prerequisites

Docker Run PostgreSQL container

You have to use Docker to run PostgreSQL databases. Below is an example command to run a PostgreSQL container:

docker run --name my-postgres-db -p 9000:5432 -e POSTGRES_PASSWORD=123456789  -e POSTGRES_USER=devopsroles  -e POSTGRES_DB=my-db -d postgres:14

Note:

  • -p 9000:5432: Host port 9000 and Container port 5432
  • Image: postgres version 14
  • Container name: my-postgres-db
  • Environment variables to configure our database: POSTGRES_USER, POSTGRES_PASSWORD, and POSTGRES_DB

The output terminal is below

Using psql command to connect the database

psql --host localhost --port 5432 --username devopsroles --dbname my-db

The output terminal is below

Your database is currently empty. I will create a table as an example

CREATE TABLE sites (id SERIAL PRIMARY KEY, name VARCHAR(100));
INSERT INTO sites (name)
  VALUES ('devopsroles.com'), ('huuphan.com');

I will run a command to query the table created.

SELECT * FROM sites;

The output terminal is below

Docker Manage data persistence

The problem is that we stop and start the container with the commands “docker stop my-postgres-db” and “docker start my-postgres-db” when creating a new container will not allow us to access the database that you are created, as it was isolated in your container.

Create a new volume with the following command. The solution stores the database outside of the container

docker volume create my-postgres-db-db

You will stop and remove your current container and create a new one.

docker stop my-postgres-db
docker rm my-postgres-db
docker run --name my-postgres-db -p 5432:5432  -e POSTGRES_PASSWORD=123456789  -e POSTGRES_USER=devopsroles  -e POSTGRES_DB=my-db -v my-postgres-db-db:/var/lib/postgresql/data -d postgres:14

How to know where the database is stored on your computer

docker inspect my-postgres-db-db

The output terminal is below

Conclusion

Using Docker to run PostgreSQL databases offers a streamlined approach to managing your database environments with ease and efficiency. I hope this tutorial has provided you with the necessary insights and steps to confidently set up and connect to PostgreSQL using Docker. Thank you for reading the  DevopsRoles page and I hope this guide proves helpful in your journey toward optimizing your development and deployment processes.

How to delete docker image with dependent child images

Today, I can’t delete docker images with dependent child images. How to delete docker image with dependent child images.

I want to delete image e16184e8dd39

[vagrant@localhost docker-flask-app]$ docker images
REPOSITORY             TAG       IMAGE ID       CREATED        SIZE
python                 3.6       e16184e8dd39   9 days ago     902MB
mysql                  5.7       938b57d64674   2 weeks ago    448MB
docker-flask-app_app   latest    44ae2f35ec29   3 weeks ago    915MB
<none>                 <none>    0e0359a5ec25   3 weeks ago    908MB
<none>                 <none>    3a59efe32b9c   3 weeks ago    908MB
postgres               latest    6ce504119cc8   5 weeks ago    374MB
odoo                   14        4f53998176ca   5 weeks ago    1.41GB
postgres               <none>    346c7820a8fb   2 months ago   315MB

I am trying with command as below

sudo docker rmi e16184e8dd39

Error delete docker image with dependent child images

[vagrant@localhost docker-flask-app]$ sudo docker rmi e16184e8dd39
Error response from daemon: conflict: unable to delete e16184e8dd39 (cannot be forced) - image has dependent child images
[vagrant@localhost docker-flask-app]$

I can not delete an image with the -f flag.

How to Fixed it

You should try to remove unnecessary images before removing the image:

[vagrant@localhost docker-flask-app]$ docker rmi $(docker images -q) -f

The output terminal as below

Note: This command above will remove images all.

After you remove the image.

docker rmi -f e16184e8dd39

Conclusion

You have to delete the docker image with dependent child images I hope will this your helpful. Thank you for reading the DevopsRoles page!

Docker setup Nginx Flask and Postgres

Introduction

In this tutorial, How to use Docker setup Nginx Flask and Postgres.

Prerequisites

Docker setup Nginx Flask and Postgres

The structure folder and file of the app.

Nginx

The first Docker Nginx. It will be used as a proxy server.

User --> Nginx --> Python application

Dockerfile file

[vagrant@localhost nginx-flask-postgres]$ cat nginx/Dockerfile
FROM nginx:latest

RUN rm /etc/nginx/conf.d/default.conf
COPY nginx/devopsroles.conf /etc/nginx/conf.d/

Example devopsroles.conf file

server {
  listen 80;
  server_name _;

  location / {
    try_files $uri @app;
  }

  location @app {
    include /etc/nginx/uwsgi_params;
    uwsgi_pass flask:8080;
  }
}

Flask

The second Docker container Python application running on a uWSGI server.

Dockerfile file

[vagrant@localhost nginx-flask-postgres]$ cat nginx/Dockerfile
FROM nginx:latest

RUN rm /etc/nginx/conf.d/default.conf
COPY nginx/devopsroles.conf /etc/nginx/conf.d/
[vagrant@localhost nginx-flask-postgres]$ cat flask/Dockerfile
# Base Image
FROM python:3.6-alpine as BASE

RUN apk add --no-cache linux-headers g++ postgresql-dev gcc build-base linux-headers ca-certificates python3-dev libffi-dev libressl-dev libxslt-dev
RUN pip wheel --wheel-dir=/root/wheels psycopg2
RUN pip wheel --wheel-dir=/root/wheels cryptography

# Actual Image
FROM python:3.6-alpine as RELEASE

EXPOSE 8080
WORKDIR /app

ENV POSTGRES_USER="" POSTGRES_PASSWORD="" POSTGRES_HOST=postgres POSTGRES_PORT=5432 POSTGRES_DB=""

COPY dist/ ./dist/
COPY flask/uwsgi.ini ./
COPY --from=BASE /root/wheels /root/wheels

RUN apk add --no-cache build-base linux-headers postgresql-dev pcre-dev libpq uwsgi-python3 && \
    pip install --no-index --find-links=/root/wheels /root/wheels/* && \
    pip install dist/*

CMD ["uwsgi", "--ini", "/app/uwsgi.ini"]

Note:

  • It exposes port 8080
  • creates a default directory /app/

uwsgi.ini file

[uwsgi]
socket = :8080
module = devopsroles.wsgi:app
master = 1
processes = 4
plugin = python

Postgres

Get Postgres the latest Postgres image from Docker Hub. Then we pass environment variables to it.

Example: database.conf file

[vagrant@localhost nginx-flask-postgres]$ cat postgres/database.conf
POSTGRES_USER=test
POSTGRES_PASSWORD=password
POSTGRES_HOST=postgres
POSTGRES_PORT=5432
POSTGRES_DB=devopsroles

The final docker-compose.yml

[vagrant@localhost nginx-flask-postgres]$ pwd
/home/vagrant/nginx-flask-postgres
[vagrant@localhost nginx-flask-postgres]$ cat docker-compose.yml
version: '3.5'

services:
  web_server:
    container_name: nginx
    build:
      context: .
      dockerfile: nginx/Dockerfile
    ports:
      - 80:80
    depends_on:
      - app

  app:
    container_name: flask
    build:
      context: .
      dockerfile: flask/Dockerfile
    env_file: postgres/database.conf
    expose:
      - 8080
    depends_on:
      - database

  database:
    container_name: postgres
    image: postgres:latest
    env_file: postgres/database.conf
    ports:
      - 5432:5432
    volumes:
      - db_volume:/var/lib/postgresql

volumes:
  db_volume:

Docker Compose Build and Run

docker-compose up --build -d

The result Docker container Nginx, Flask, and Postgres

Conclusion

You have Deploy Docker setup Nginx Flask and Postgres. I hope will this your helpful. Thank you for reading the DevopsRoles page!

Deploy Flask-MySQL app with docker-compose

Introduction

In this tutorial, How to deploy Flask-MySQL app with docker-compose. From the official docs. Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services. Then, with a single command, you create and start all the services from your configuration. The fist, You need to install Docker and docker-compose. Next, we will Deploy Flask-MySQL app.

The folder and file structure of the app

[vagrant@localhost ~]$ tree docker-flask-app
docker-flask-app
├── app
│   ├── app.py
│   ├── Dockerfile
│   └── requirements.txt
├── db
│   └── init.sql
└── docker-compose.yml

2 directories, 5 files
[vagrant@localhost ~]$
  • File app.py is the Flask app which connect to database and exposes on REST API endpoint.
  • init.sql an SQL script to initialize the database before run app.

The content of app.py and init.sql as below

[vagrant@localhost docker-flask-app]$ cat app/app.py
from typing import List, Dict
from flask import Flask
import mysql.connector
import json

app = Flask(__name__)

def test_table() -> List[Dict]:
    config = {
        'user': 'root',
        'password': 'root',
        'host': 'db',
        'port': '3306',
        'database': 'devopsroles'
    }
    connection = mysql.connector.connect(**config)
    cursor = connection.cursor()
    cursor.execute('SELECT * FROM test_table')
    results = [{name: color} for (name, color) in cursor]
    cursor.close()
    connection.close()

    return results


@app.route('/')
def index() -> str:
    return json.dumps({'test_table': test_table()})


if __name__ == '__main__':
    app.run(host='0.0.0.0')
[vagrant@localhost docker-flask-app]$ cat db/init.sql
create database devopsroles;
use devopsroles;

CREATE TABLE test_table (
  name VARCHAR(20),
  color VARCHAR(10)
);

INSERT INTO test_table
  (name, color)
VALUES
  ('dev', 'blue'),
  ('pro', 'yellow');

Create a Docker image for Flask app

Create a Dockerfile file in the app folder.

[vagrant@localhost docker-flask-app]$ cat app/Dockerfile
# Use an official Python runtime as an image
FROM python:3.6

# The EXPOSE instruction indicates the ports on which a container
EXPOSE 5000

# Sets the working directory for following COPY and CMD instructions
# Notice we haven’t created a directory by this name - this instruction
# creates a directory with this name if it doesn’t exist
WORKDIR /app

COPY requirements.txt /app
RUN python -m pip install --upgrade pip
RUN pip install --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host=files.pythonhosted.org --no-cache-dir -r requirements.txt

# Run app.py when the container launches
COPY app.py /app
CMD python app.py

You need dependencies Flask and mysql-connector in File requirements.txt

[vagrant@localhost docker-flask-app]$ cat app/requirements.txt
flask
mysql-connector

Create a docker-compose.yml

[vagrant@localhost docker-flask-app]$ cat docker-compose.yml
version: "2"
services:
  app:
    build: ./app
    links:
      - db
    ports:
      - "5000:5000"
  db:
    image: mysql:5.7
    ports:
      - "3306:3306"
    environment:
      MYSQL_ROOT_PASSWORD: root
    volumes:
      - ./db:/docker-entrypoint-initdb.d/:ro

Running the Flask app

[vagrant@localhost docker-flask-app]$ docker-compose up -d

The result, after running the Flask app

FAQs

1. What is Docker-Compose?

Docker-Compose is a tool for defining and running multi-container Docker applications. It allows you to configure your application’s services in a YAML file and start all services with a single command.

2. How can I persist data in MySQL?

In the Docker-Compose file, the db_data volume ensures that the data in MySQL is persisted even if the container is stopped.

3. Can I use a different database with Flask?

Yes, Flask can work with various databases like PostgreSQL, SQLite, and more. You need to adjust the connection setup in your Flask app and Docker-Compose file accordingly.

Conclusion

You have Deploy Flask-MySQL app with docker-compose. I hope will this your helpful. Thank you for reading the DevopsRoles page!

Devops Tutorial

Exit mobile version