Skip to content

Instantly share code, notes, and snippets.

@min-ji-kim
Last active February 29, 2020 06:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save min-ji-kim/6e6e5a58bcf55e50b9ebce9c108c762c to your computer and use it in GitHub Desktop.
Save min-ji-kim/6e6e5a58bcf55e50b9ebce9c108c762c to your computer and use it in GitHub Desktop.
docker-compose로 flask와 mongodb 연동 app 만들기

docker-compose로 flask와 mongodb 연동 app 만들기

> docker, docker-compose 설치

ubuntu 16.04 (os)에 설치

# docker 설치 (ubuntu)
~$ sudo apt install docker

# docker-compose 설치(ubuntu)
~$ sudo apt install docker-compose

linuxmint 17.03 (os)에 설치

# docker 설치 (limuxmint)
~$ sudo apt-get remove docker docker-engine docker.io containerd runc
~$ sudo apt-get update
~$ sudo apt-get install \
    apt-transport-https \
    ca-certificates \
    curl \
    gnupg-agent \
    software-properties-common
~$ sudo apt install curl
~$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
~$ sudo apt-key fingerprint 0EBFCD88
# 주의 아래 문장은 한번만 입력
~$ sudo add-apt-repository \
"deb [arch=amd64] [https://download.docker.com/linux/ubuntu](https://download.docker.com/linux/ubuntu)  \
trusty \ 
stable"
~$ sudo apt-get update
~$ sudo apt-get install docker-ce

# docker-compose 설치 (limuxmint)
```sh
~$ curl https://github.com/docker/compose/releases/download/1.23.2/docker-compose
~$ sudo chmod +x /usr/local/bin/docker-compose

docker, docker-compose 설치 확인

# docker 설치 확인
~$ docker --version

# docker-compose 설치 확인
~$ docker-compose --version

docker-compose 설치 (centos7)

~$ curl -L https://github.com/docker/compose/releases/download/1.14.0/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
~$ chmod +x /usr/local/bin/docker-compose
~$ docker-compose --version

> 폴더 및 파일 setting

# 'mkdir 폴더명' 폴더명으로 폴더 생성
~$ mkdir todo
~$ cd todo/

# 'touch 파일명' 파일명으로 파일 생성
~$ touch app.py
~$ touch config.py

# 'mkdir 폴더명' 폴더명으로 폴더 생성
~$ mkdir templates

# flask 사용 시 html 파일은 templates 폴더 안에서 사용
~$ touch templates/todo.html

# Docker는 Dockerfile이라는 명칭의 파일을 찾아 build할 때 사용 
~$ touch Dockerfile

# docker-compose.yml은 services, networks, volumes를 정의하기 위해 사용
~$ touch docker-compose.yml

# python 라이브러리를 requirement.txt 파일에 저장해두고 쉽게 install 하기 위해 생성
~$ touch requirement.txt

# vim 설치
~$ sudo apt install vim

> app.py 파일 작성

# app.py 파일 작성
~$  sudo vi app.py 
#-*- coding:utf-8 -*_
from flask import Flask, redirect, url_for, request, render_template
from pymongo import MongoClient
import os

app = Flask(__name__)

# docker-compose.yml 파일에 따라 Dockerfile build 후 생성된 컨테이너에서 os.envrion() 함수로 mongodb에 설정된 ip주소를 확인
client = MongoClient(os.environ['DB_PORT_27017_TCP_ADDR'], 27017)
db = client.tododb

@app.route('/')
def todo():
	_items = db.tododb.find()
	items = [item for item in _items]
	return render_template('todo.html', items=items)
   
# templeates/todo.html 파일에서 form에 입력 시 new() 메소드 실행 
@app.route('/new',methods=['POST'])
def new():
	item_doc = {
		'name': request.form['name'],
		'description': request.form['description']
	}
# item_doc dictionary를 mongodb에 insert
	db.tododb.insert_one(item_doc)
# redirect로 재전송
# url_for() 메소드로 todo() method를 실행    
        return redirect(url_for('todo'))

if __name__ == "__main__":
        app.run(host='0.0.0.0', debug=True)

> requirement.txt 파일 작성

# requirement.txt 파일 작성
~$ sudo vi requirement.txt 
flask
pymongo

> Dockerfile 파일 작성

# Dockerfile 파일 작성
~$ vi Dockerfile 
FROM python:2.7
ADD . /todo
WORKDIR /todo
RUN pip install -r requirement.txt

> docker-compose.yml 파일 작성

# docker-compose.yml 파일 작성
~$ sudo vi docker-compose.yml
web:  
  build: .
  command: python -u app.py
  ports:
    - "5000:5000"
  volumes:
    - .:/todo
  links:
    - db
db:
  image: mongo:3.0.2

> templates/todo.html 파일 작성

<!doctype html>

<form action="/new" method="POST">
  <input type="text" name="name"></input>
  <input type="text" name="description"></input>
  <input type="submit"></input>
</form>

{% for item in items %}
  <h1> {{ item.name }} </h1>
  <p> {{ item.description }} <p>
{% endfor %}

> docker-compose 파일 실행

# docker 실행
~$ sudo service docker start
# todo 디렉토리에 있는 docker-compose.yml 파일 실행
~$ cd /todo
~$ sudo docker-compose up

> 웹브라우저에서 실행

http://0.0.0.0:5000/

참고동영상

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment