Docker Community Forums

Share and learn in the Docker community.

Flask in network_mode: "Host"

version: "3"

services:

  db:

    build:

      context: ./db

      dockerfile: Dockerfile

    volumes:

      - "mongo-data:/data/db"

    network_mode: "host"

    ports:

      - "27017:27017"

  python:

    build: 

      context: ./python

      dockerfile: Dockerfile

    # network_mode: "host"

    container_name: flasktest

    ports:

      - "5000:5000"

volumes: 

  mongo-data:

This is how to docker file looks like, but my problem is when I put network_mode: “host” in my python container, my flask website does not work.

import gc

import datetime

from typing import Any

from pymongo import MongoClient, errors

from flask import Flask, render_template

app = Flask(__name__)

try:

    # client = MongoClient("mongodb://db:27017")

    client = MongoClient("mongodb://localhost:27017/db")

    # client = MongoClient()

except errors.ConnectionFailure as ef:

    print(ef)

except errors.ServerSelectionTimeoutError as sste:

    print(sste)

else:

    print("[CONNECTED TO MONGO CLIENT]")

    db = client.Yoyo

    col = db.beacondata

    print("[DATABASE CREATED]")

class ToDatabase:

    def __init__(self, major: Any, minor: Any) -> None:

        self.major = major

        self.minor = minor

        self.timestamp = str(datetime.datetime.utcnow())

    def insert_data(self) -> None:

        data = {

            'Major': self.major,

            'Minor': self.minor,

            'Timestamp': self.timestamp

        }

        data_id = col.insert_one(data).inserted_id

        print(f"[DATA INSERTED] - object_id - {data_id}")

        gc.collect()

    def exists(self):

        if col.find({'Major': self.major, 'Minor': self.minor}).count() > 0:

            print(f"[DOCUMENT EXISTS] - {self.major}{self.minor}")

        else:

            print(f"[DOCUMENT DOES NOT EXISTS] - {self.major}{self.minor}")

            self.insert_data()

    @staticmethod

    def fetch_data_from_db() -> None:

        for data in col.find():

            print(data)

    @staticmethod

    def drop_col() -> None:

        col.drop()

        if 'data' not in db.list_collection_majors():

            print("[SUCESSFULLY DROPPED COLLECTION]")

def main():

    major = ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10']

    minor = ['21', '22', '22', '21', '23', '21', '22', '22', '21', '23', '30']

    for i in range(len(major)):

        obj = ToDatabase(major[i], minor[i])

        obj.exists()

    obj.fetch_data_from_db()

@app.route('/')

def index():

    records = col.find()

    return render_template('index.html', names=records)

if __name__ == '__main__':

    main()

    app.run(debug=True, host='0.0.0.0')

I want to know how can I run my flask app with network mode host