LoginSignup
1
6

More than 1 year has passed since last update.

Docker初心者がVagrant、Docker、Django、Python 、PostgreSQLで環境構築

Last updated at Posted at 2021-06-30

今回、アプリケーション制作するために、初めてDockerを使ってみて仮想環境構築したので、
自分用の備忘録として、手順を残しておこうと思います。

あくまで環境構築の手順を示したもので、しっかりした内容のものであれば他の記事を参考にされた方が良いかと思われます。

とにかく、早く環境構築したい、と思った方向けの記事です。

なぜVagrantを使うのか

仮想環境構築を共有しやすい

Windowsだと、Windowsの環境、MacではMacの環境といって環境依存されやすいというdockerの弱みを
vagrantを使って仮想マシンを構築することによって、環境に左右されない環境ができます。

うまくいかなくなっても環境をすぐぶっ壊せる

Vagrantは一度環境構築してもvagrant destroyで仮想環境を破棄することが可能です。
何かあってもテストしやすい環境なので、とても便利です。

 今回、参考にさせていただいたサイト

なかなかvagrantとdockerを組み合わせて使う環境構築が比較的早く済む方法が見つからず苦戦しまくりました。

やっと見つけたサイトでとても参考にさせていただいたサイトがあったためリンクを貼っておきます。

ほぼ、設定は同じですが、一部エラーが出たり、サイトがきちんと表示されずエラーとなってしまう不具合もあったため
設定を変える必要があったため、こちらの記事にどういった状況でエラーが出たのか、エラーを解決する方法を記載しました。

準備

事前知識

  • ターミナル操作の基礎知識

インストール

それぞれインストール

なくてもいいがあったら便利なもの
- Visual Studio Code

Vagrantのプラグインインストール

ターミナルを開きコマンドを入力

vagrant plugin install vagrant-vbguest
vagrant plugin install vagrant-docker-compose

vagrant plugin listでプラグインをインストールされているかどうか確認します

vagrant-vbguest (0.30.0, global)
vagrant-docker-compose (1.5.1, global)

作業フォルダを作成

作業したい場所に、適宜フォルダとファイルを作成します
今回は以下のように設定しました

ディレクトリ
> tree
├── vagrant
│   ├── docker-compose.yml
│   ├── Dockerfile
├___├── Vagrantfile

作成したファイルは以下のように記述して保存します。

Dockerfile

vagrant/Dockerfile
FROM python
RUN apt -y update
RUN apt install -y postgresql libpq-dev
RUN pip install psycopg2
RUN apt install -y  python3-django
RUN pip install django

docker-compose.yml

vagrant/docker-compose.yml
version: "3"
services:
  app:
    build: .
    image: app-img
    container_name: app
    ports:
      - 80:80
    volumes:
      - /vagrant/test:/test
    working_dir: /test
    command: python manage.py runserver 0.0.0.0:80
    restart: always
    depends_on:
      - db
  db:
    image: postgres
    container_name: db
    ports:
      - 5432:5432
    volumes:
      - db-vol:/var/lib/postgresql/data
    environment:
      POSTGRES_USER: vagrant
      POSTGRES_PASSWORD: vagrant
      POSTGRES_DB: test_db
    restart: always
volumes:
  db-vol:

Vagrantfile

Djangoでlocalhost接続ができないため、今回仮想環境にアクセスするためのipアドレスを設定しています

vagrant/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :

# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure("2") do |config|
  # The most common configuration options are documented and commented below.
  # For a complete reference, please see the online documentation at
  # https://docs.vagrantup.com.

  # Every Vagrant development environment requires a box. You can search for
  # boxes at https://vagrantcloud.com/search.

  # 軽さ優先でUbuntuにしたが、centosで実行したいなら下記に変更
  # config.vm.box = "centos/7"
    config.vm.box = "ubuntu/focal64"
  # Disable automatic box update checking. If you disable this, then
  # boxes will only be checked for updates when the user runs
  # `vagrant box outdated`. This is not recommended.
  # config.vm.box_check_update = false

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine. In the example below,
  # accessing "localhost:8080" will access port 80 on the guest machine.
  # NOTE: This will enable public access to the opened port
  # config.vm.network "forwarded_port", guest: 80, host: 8080

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine and only allow access
  # via 127.0.0.1 to disable public access
  # config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1"

  # Create a private network, which allows host-only access to the machine
  # using a specific IP.
  # localhostだとうまく作動していなかっため、IP指定
  config.vm.network "private_network", ip: "192.168.33.10"

  # 共有フォルダの設定
  config.vm.synced_folder ".", "/vagrant", type:"virtualbox"

  # 仮想マシン内のサーバーにアクセスするための設定
  config.vm.network "forwarded_port", guest: 80, host: 80, host_ip: "127.0.0.1"
  config.vm.network "forwarded_port", guest: 5432, host: 5432

  # dockerを使えるようにする
  config.vm.provision :docker
  config.vm.provision :docker_compose, yml: "/vagrant/docker-compose.yml", run: "always"

  # Create a public network, which generally matched to bridged network.
  # Bridged networks make the machine appear as another physical device on
  # your network.
  # config.vm.network "public_network"

  # Share an additional folder to the guest VM. The first argument is
  # the path on the host to the actual folder. The second argument is
  # the path on the guest to mount the folder. And the optional third
  # argument is a set of non-required options.
  # config.vm.synced_folder "../data", "/vagrant_data"

  # Provider-specific configuration so you can fine-tune various
  # backing providers for Vagrant. These expose provider-specific options.
  # Example for VirtualBox:
  #
  # config.vm.provider "virtualbox" do |vb|
  #   # Display the VirtualBox GUI when booting the machine
  #   vb.gui = true
  #
  #   # Customize the amount of memory on the VM:
  #   vb.memory = "1024"
  # end
  #
  # View the documentation for the provider you are using for more
  # information on available options.

  # Enable provisioning with a shell script. Additional provisioners such as
  # Ansible, Chef, Docker, Puppet and Salt are also available. Please see the
  # documentation for more information about their specific syntax and use.
  # config.vm.provision "shell", inline: <<-SHELL
  #   apt-get update
  #   apt-get install -y apache2
  # SHELL
end

起動

Vagrantfileと同じカレントディレクトリでvagrant upとターミナルに打ちます。

vagrant statusrunningと表示されていれば問題ありません。

続いてvagrant sshというコマンドをターミナルで叩きます。
パスワードが求められる場合、vagrantと入力すれば接続可能です。

まずlinuxにアクセスできたら、共有フォルダに移動します。
そしてビルドします。

$ cd /vagrant
$ docker-compose build

きちんとインストールされたか確認します。

$ docker-compose run --rm app python --version
・・・
Python 3.9.4

$ docker-compose run --rm app pip --version
・・・
pip 21.1 from /usr/local/lib/python3.9/site-packages/pip (python 3.9)

プロジェクトを作成します。

docker-compose run --rm app django-admin startproject sample_app

ここで、おかしな点が出てきます。
原因がよくわかっておりません。

ディレクトリ
> tree
├── vagrant
│   ├── docker-compose.yml
│   ├── Dockerfile
├___├── Vagrantfile
├___├── test
├___├── ├── sample_api
├___├── ├──  ├── sample_api
├___├── ├──  ├── manage.py

testの下にsample_apiが二つできています。
このsample_apiを下記のようにディレクトリを調整します。
ターミナルでコマンド操作してもいけますが、共有フォルダの設定になっているので
ホスト側の作業用フォルダからでも編集はいけます。

ディレクトリ
> tree
├── vagrant
│   ├── docker-compose.yml
│   ├── Dockerfile
├___├── Vagrantfile
├___├── test
├___├── ├── manage.py
├___├── ├── sample_api

sample_apiにある、settings.pyのDATABASESを下記のように編集します。

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'test_db',
        'USER': 'vagrant',
        'PASSWORD': 'vagrant',
        'HOST': 'db',
        'PORT': '',
    }
}

さらに、ALLOWED_HOSTSを下記のように編集します。

ALLOWED_HOSTS = ['192.168.33.10']

設定が終わりましたら、マイグレーションを実行します。
※マイグレーションした後にdbの設定を書き換えるとエラーが出てしまいます。
dockerを作り直す必要が出てくるため、注意が必要です。

DjangoでPostgreSQLのパスワード認証が通らない

docker-compose run --rm app python manage.py migrate
docker-compose up -d

http://192.168.33.10にアクセスするとDjangoの画面が表示されます。

django.png

終了する時

ssh接続を切るためにターミナルからexitを入力してvagrant haltとすると終了できます。

1
6
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
1
6