Showing posts with label mongodb. Show all posts
Showing posts with label mongodb. Show all posts

Friday

Microservices Application with Flutter Flask MongoDB RabbitMQ

A complete microservice application setup with a Flutter app, MongoDB, and RabbitMQ, along with all the necessary files and folder structure. The setup uses Docker Compose to orchestrate the services.


Folder Structure

```

microservice-app/

├── backend/

│   ├── Dockerfile

│   ├── requirements.txt

│   ├── main.py

│   └── config.py

├── frontend/

│   ├── Dockerfile

│   ├── pubspec.yaml

│   └── lib/

│       └── main.dart

├── docker-compose.yml

└── README.md

```


1. `docker-compose.yml`

```yaml

version: '3.8'


services:

  backend:

    build: ./backend

    container_name: backend

    ports:

      - "8000:8000"

    depends_on:

      - mongodb

      - rabbitmq

    environment:

      - MONGO_URI=mongodb://mongodb:27017/flutterdb

      - RABBITMQ_URI=amqp://guest:guest@rabbitmq:5672/

    networks:

      - microservice-network


  mongodb:

    image: mongo:latest

    container_name: mongodb

    ports:

      - "27017:27017"

    networks:

      - microservice-network


  rabbitmq:

    image: rabbitmq:3-management

    container_name: rabbitmq

    ports:

      - "5672:5672"

      - "15672:15672"

    networks:

      - microservice-network


  frontend:

    build: ./frontend

    container_name: frontend

    ports:

      - "8080:8080"

    depends_on:

      - backend

    networks:

      - microservice-network


networks:

  microservice-network:

    driver: bridge

```


2. Backend Service


2.1 `backend/Dockerfile`

```dockerfile

FROM python:3.9-slim


WORKDIR /app


COPY requirements.txt requirements.txt

RUN pip install -r requirements.txt


COPY . .


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

```


2.2 `backend/requirements.txt`

```txt

fastapi

pymongo

pika

uvicorn

```


2.3 `backend/config.py`

```python

import os


MONGO_URI = os.getenv('MONGO_URI')

RABBITMQ_URI = os.getenv('RABBITMQ_URI')

```


2.4 `backend/main.py`

```python

from fastapi import FastAPI

from pymongo import MongoClient

import pika

import config


app = FastAPI()


client = MongoClient(config.MONGO_URI)

db = client.flutterdb


# RabbitMQ Connection

params = pika.URLParameters(config.RABBITMQ_URI)

connection = pika.BlockingConnection(params)

channel = connection.channel()


@app.get("/")

async def read_root():

    return {"message": "Backend service running"}


@app.post("/data")

async def create_data(data: dict):

    db.collection.insert_one(data)

    channel.basic_publish(exchange='', routing_key='flutter_queue', body=str(data))

    return {"message": "Data inserted and sent to RabbitMQ"}

```


3. Frontend Service


3.1 `frontend/Dockerfile`

```dockerfile

FROM cirrusci/flutter:stable


WORKDIR /app


COPY . .


RUN flutter build web


CMD ["flutter", "run", "-d", "chrome"]

```


3.2 `frontend/pubspec.yaml`

```yaml

name: flutter_app

description: A new Flutter project.


version: 1.0.0+1


environment:

  sdk: ">=2.7.0 <3.0.0"


dependencies:

  flutter:

    sdk: flutter

  http: ^0.13.3


dev_dependencies:

  flutter_test:

    sdk: flutter

```


#### 3.3 `frontend/lib/main.dart`

```dart

import 'package:flutter/material.dart';

import 'package:http/http.dart' as http;


void main() {

  runApp(MyApp());

}


class MyApp extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return MaterialApp(

      title: 'Flutter Demo',

      theme: ThemeData(

        primarySwatch: Colors.blue,

      ),

      home: MyHomePage(),

    );

  }

}


class MyHomePage extends StatefulWidget {

  @override

  _MyHomePageState createState() => _MyHomePageState();

}


class _MyHomePageState extends State<MyHomePage> {

  Future<void> sendData() async {

    final response = await http.post(

      Uri.parse('http://backend:8000/data'),

      body: {'key': 'value'},

    );

    print('Response status: ${response.statusCode}');

    print('Response body: ${response.body}');

  }


  @override

  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(

        title: Text('Flutter Microservice App'),

      ),

      body: Center(

        child: ElevatedButton(

          onPressed: sendData,

          child: Text('Send Data to Backend'),

        ),

      ),

    );

  }

}

```


4. `README.md`

```markdown

# Microservice Application


## Overview


This is a microservice application setup consisting of a Flutter app (frontend), a FastAPI service (backend), MongoDB, and RabbitMQ. All services are orchestrated using Docker Compose.


## How to Run


1. Clone the repository:

   ```bash

   git clone https://github.com/your-repo/microservice-app.git

   cd microservice-app

   ```


2. Build and run the containers:

   ```bash

   docker-compose up --build

   ```


3. Access the services:

   - Frontend: `http://localhost:8080`

   - Backend: `http://localhost:8000`

   - RabbitMQ Management: `http://localhost:15672`

   - MongoDB: `mongodb://localhost:27017`

```


### Instructions to Run the Application

1. Ensure Docker and Docker Compose are installed on your machine.

2. Place the folder structure and files as described above.

3. Navigate to the root of the `microservice-app` folder.

4. Run `docker-compose up --build` to build and start the application.

5. Access the frontend on `http://localhost:8080`, backend on `http://localhost:8000`, and RabbitMQ Management UI on `http://localhost:15672`.


This setup provides a working microservice application with a Flutter frontend, FastAPI backend, MongoDB for storage, and RabbitMQ for messaging.

Tuesday

How To Get the MongoDB Version from Another Docker Container


To get the MongoDB version from outside of MongoDB in the terminal, you can use the following commands:

Linux and macOS:

mongo --version

Windows:

mongod --version

These commands will print the version of MongoDB that is installed on your system.

For example, if you are running MongoDB version 5.0.13, the command will output the following:

MongoDB server version: 5.0.13

If you are running the MongoDB Compass GUI, you can also get the MongoDB version by clicking on the Help menu and selecting About MongoDB Compass.

There are a few ways to get the MongoDB version from another container when the MongoDB is running on a separate container and the other container is running a Debian-based image with Python:

  1. Use the mongo command. You can use the mongo command to connect to the MongoDB container and get the version. To do this, you will need to know the IP address of the MongoDB container. You can get the IP address of the container using the docker inspect command.
docker inspect mongodb

Once you have the IP address of the MongoDB container, you can use the following command to connect to the container and get the version:

mongo --host <mongodb_container_ip_address> --version
  1. Use the mongod command. You can also use the mongod command to get the version of MongoDB. To do this, you will need to know the port that MongoDB is running on. You can get the port that MongoDB is running on using the docker inspect command.
docker inspect mongodb

Once you have the port that MongoDB is running on, you can use the following command to get the version of MongoDB:

mongod --port <mongodb_container_port> --version
  1. Use the Python MongoClient. You can also use the Python MongoClient to get the version of MongoDB. To do this, you will need to install the MongoClient package.
pip install pymongo

Once you have installed the MongoClient package, you can use the following code to get the version of MongoDB:

Python
import pymongo

client = pymongo.MongoClient('mongodb://<mongodb_container_ip_address>:<mongodb_container_port>')
db = client.test
print(db.version())

Which method you use to get the version of MongoDB depends on your specific needs and requirements.

Yes, it is possible to get the MongoDB version from another container using a shell script. Here is a simple example:

#!/bin/bash

# Get the IP address of the MongoDB container
mongodb_container_ip_address=$(docker inspect mongodb -f '{{.NetworkSettings.IPAddress}}')

# Get the version of MongoDB
mongodb_version=$(mongo --host $mongodb_container_ip_address --version)

# Print the version of MongoDB
echo "MongoDB version: $mongodb_version"

This shell script will first get the IP address of the MongoDB container using the docker inspect command. Then, it will use the mongo command to connect to the MongoDB container and get the version. Finally, it will print the version of MongoDB to the console.

You can save this shell script as a file, such as get_mongodb_version.sh, and then run it using the following command:

bash get_mongodb_version.sh

This will print the version of MongoDB to the console.

You can also use this shell script in other scripts or applications to get the version of MongoDB from another container. For example, you could use this shell script in a CI/CD pipeline to verify that the correct version of MongoDB is running before deploying your application.