0
0

More than 5 years have passed since last update.

Dockerを使ってみよう-1

Posted at

この記事は Dockerを分かった気になれる Dockerのコンセプトとかあまり紹介しないまま、脳死コピペでなんとかいける仕様になってます。今回はDockerをインストールし、コンテナを作って起動させるところまで書きます。
次回はAWSのECRにコンテナをプッシュする作業について書きたいと思います。

仕事でDockerを使えって言われたけど、どこから手を付ければいいのか分からなかった数日前の自分のために…

環境

・Amazon Linux AMI 2018.03.0 (HVM)
・Docker CE
・ポート4000

Dockerをインストール

最初からスーパーユーザーになってたら楽かもしれませんね。

アプデ
sudo yum update
インストール
sudo yum install docker -y
Docker起動
sudo service docker start

Docker Imageを作成

ここではDockerfilerequirements.txtapp.pyのファイルを三種類を作り、編集していきます
以下のコードはDocker公式のドキュメントから拝借しています。リンクは記事の一番下にあるのでぜひ見に行ってくださいね!
コードの詳細が書かかれてますよ(英語)

ファイルを作成

touch Dockerfile

内容はこれに編集します

Dockerfile

# Use an official Python runtime as a parent image
FROM python:2.7-slim

# Set the working directory to /app
WORKDIR/app

# Copy the current directory contents into the container at /app
COPY. /app

# Install any needed packages specified in requirements.txt
RUN pip install --trusted-hostpypi.python.org -rrequirements.txt

# Make port 80 available to the world outside this container
EXPOSE80

# Define environment variable
ENVNAME World

# Run app.pywhen the container launches
CMD["python", "app.py"]

requirements.txtも作り、編集していきます

requirements.txt
Flask
Redis

app.pyも同様です

app.py

from flask import Flask
from redis import Redis,RedisError
import os 
import socket
# Connect to Redis
redis = Redis(host="redis", db=0, socket_connect_timeout=2, socket_timeout=2)

app=Flask(__name__)

@app.route("/")
def hello():
    try:
        visits = redis.incr("counter")
    except RedisError:
        visits = "<i>cannot connect to Redis, counter disabled</i>"

    html = "<h3>Hello {name}!</h3>"\
            "<b>Hostname:</b> {hostname}<br/>"\
            "<b>Visits:</b{visits}"
   return html.format(name=os.getenv("NAME","world"),
hostname = socket.gethostname(), visits=visits)

if__name__=="__main__":

    app.run(host='0.0.0.0',port=80)

Dockerを走らせます

いよいよですよ…

まずはビルドから

friendlyhelloのタグをつけてやりますので、タグの名前を変更しても大丈夫です

docker build -t friendlyhello .

Docker imagesでビルドを確認します

docker images

先ほどつけた名前がREPOSITORYの下にでますので、ちゃんとありましたら走らせます!!!!
ポート4000を使うのでEC2インスタンスの方でもちゃんと開けておいてくださいね

docker run -p 4000:80 friendlyhello

アウトプットに'#Running on http://0.0.0.0.80/ (Press CTRL+C to quit)' がでましたら、インスタンスのPublic IP アドレスとポート番号を指定して実際にHello World!が表示されてるか確認しにいきましょう

簡単にいうとこんな感じです↓
http://your_public_ip:4000/

参考にしたサイト

この記事で使用したコードはDocker公式のご提供です
https://docs.docker.com/get-started/part2/

アマゾンさんは日本語に対応していますので
https://docs.aws.amazon.com/AmazonECS/latest/developerguide/docker-basics.html

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0