본문 바로가기

23년 2학기 학교공부/컴퓨터네트워크

[CN] Web Service Deployment

목차

    728x90
    반응형
    SMALL

    🍂 웹 서버 배포

     

     

     

     

     

    🍂 docker network 생성

    $ docker network create --drver=bridge mybridge

     

     

     

     

     

    🍂 python app server 배포

     

    http_server 파이썬 서버 코드를 직접 작성하여 mycounter라는 컨테이너에 배포해보자.

     

    # http_server.py
    
    import os
    import http
    import http.server
    import socketserver
    import sqlite3
    
    PREFIX = ''
    
    FLAGS = _ = None
    DEBUG = False
    
    EXT = {'.html': 'text/html;charset=utf-8'}
    
    CONN = sqlite3.connect('./Log.db')
    CUR = CONN.cursor()
    CUR.execute('''CREATE TABLE IF NOT EXISTS Log (
                     id INTEGER PRIMARY KEY AUTOINCREMENT,
                     ip TEXT,
                     request TEXT);''')
    CONN.commit()
    
    
    class MyHTTPDaemon(http.server.HTTPServer):
        allow_reuse_address = True
    
    
    class MyHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
        def __init__(self, *args, **kwargs):
            self.rootdir = FLAGS.rootdir
            self.conn = CONN
            self.cur = CUR
            super().__init__(*args, **kwargs)
    
        def do_GET(self):
            if DEBUG:
                print(f'Command: {self.command}')
                print(f'Path: {self.path}')
                print(f'Headers: {self.headers}')
    
            self.cur.execute('''INSERT INTO Log (ip, request)
                                VALUES (?, ?);''', (self.client_address[0], self.requestline))
            self.conn.commit()
    
            if not self.path.startswith(PREFIX):
                return None
            self.path = self.path[len(PREFIX):]
            if self.path == '/':
                path = 'index.html'
            else:
                path = self.path[1:]
            path = os.path.join(self.rootdir, path)
            if DEBUG:
                print(f'Joined path: {self.rootdir} {self.path} {path}')
            if not os.path.exists(path):
                self.send_error(http.HTTPStatus.NOT_FOUND, 'File not found')
            else:
                ext = os.path.splitext(path)[-1].lower()
                self.send_response(http.HTTPStatus.OK)
                self.send_header('Content-Type', EXT[ext])
                with open(path, 'rb') as f:
                    self.cur.execute('''SELECT MAX(id) FROM Log;''')
                    counter = self.cur.fetchone()[0]
                    body = f.read()
                    body = body.replace('{{ COUNTER }}'.encode('utf-8'), f'{counter}'.encode('utf-8'))
                    self.send_header('Content-Length', len(body))
                    self.end_headers()
                    self.wfile.write(body)
    
    def main():
        print(f'Parsed arguments: {FLAGS}')
        print(f'Unparsed arguments: {_}')
    
        with MyHTTPDaemon((FLAGS.host, FLAGS.port), 
                          MyHTTPRequestHandler) as httpd:
            try:
                print(f'Start server {httpd.server_address}')
                httpd.serve_forever()
            except KeyboardInterrupt:
                print(f'Stop server {httpd.server_address}')
                httpd.shutdown()
    
    
    if __name__ == '__main__':
        import argparse
    
        parser = argparse.ArgumentParser()
        parser.add_argument('--debug', action='store_true',
                            help='Debug message')
        parser.add_argument('--host', default='0.0.0.0', type=str,
                            help='IP address')
        parser.add_argument('--port', default=8888, type=int,
                            help='Port number')
        parser.add_argument('--rootdir', default='./dir', type=str,
                            help='Root directory')
    
        FLAGS, _ = parser.parse_known_args()
        DEBUG = FLAGS.debug
    
        main()

     

     

     

    서버를 ubuntu 환경에서 실행하려고 한다.

    먼저 ubuntu 도커 이미지를 pull 받은 후, ubuntu 이미지를 기반으로 하는 도커 컨테이너인 mycounter를 생성한다.

     

    $ docker pull ubuntu:22.04
    $ docker run -itd --name mycounter --network mybridge -v [http_server.py 파일이 있는 로컬 위치]:/media/http_server --publish 4000:8888 ubuntu:22.04

     

     

     

    도커 컨테이너 리스트를 

     

     

     

     

     

     

     

     

     

     

     

    IN mydb9

    apt update
    apt install python3.10 python3-pip
    pip install uvicorn fastapi sqlalchemy
    apt-get install -y libmariadb-dev
    pip install mariadb

    apt install python3-dev python3-venv python3-pip net-tools vim

    apt install libmariadb-dev

    pip3 install fastapi uvicorn mariadb SQLAlchemy alembic

     

    $ docker pull mariadb

    $ docker run --name pastebindb -p 3306:3306 -e MARIADB_ROOT_PASSWORD=my-secret-pw -d mariadb:latest

    $ docker exec -it pastebindb bash

    $ mariadb -uroot -p

    $ CREATE DATABASE pastebin;

    $ CREATE USER IF NOT EXISTS pasteuser@pastebin IDENTIFIED BY 'user-secret-pw';

    $ SHOW WARNINGS;

    $ GRANT ALL PRIVILEGES ON pastebin.* TO 'pasteuser'@'%' IDENTIFIED BY 'user-secret-pw';

    $ FLUSH PRIVILEGES;

     

    IN myback9

    apt update
    apt install python3.10 python3-pip
    pip install uvicorn fastapi sqlalchemy

    apt-get install -y libmariadb-dev
    pip install mariadb

    apt install python3-dev python3-venv python3-pip net-tools vim

    pip3 install fastapi uvicorn mariadb SQLAlchemy alembic

     

     

    728x90
    반응형
    LIST