20210912のdockerに関する記事は9件です。

MacでBlazorServer使ってみる

はじめに 会社でBlazor開発をすることになったが家にMacBookしかなかったので、 作業概要を備忘録として残します。 環境 macOS Big Sur 11.5.2 dotnet 5.0 Docker for desktop SQLServer Homebrew VsCode ※ VisualStudio for Macは有料だったので使わない。 ※ Homebrew,VsCode,Monoの環境構築はすでに終わっていたので省く 環境構築 Docker for desktop Homebrewからインストール インストールしたら、Lanchpadからアイコン探して実行 ※ docker-composeもセットで入る $ brew install docker $ brew cask install docker SQLServer(Dockerコンテナ) 下記を参考に必要最低限でファイルを作成 参考 https://qiita.com/urushibata/items/2d499e057fe9ed0cde64 docker-compose.yml version: '3' services: mssql: image: mcr.microsoft.com/mssql/server:2019-latest container_name: mssql2019 environment: - MSSQL_SA_PASSWORD=[password] - ACCEPT_EULA=Y - MSSQL_PID=Express - MSSQL_COLLATION=Japanese_CI_AS hostname: db-server restart: always ports: - 1433:1433 volumes: - ./log:/var/opt/mssql/log - ./data:/var/opt/mssql/data 下記のコマンドでコンテナ起動 $ cd [docker-compose.ymlのあるディレクトリ] $ docker-compose up -d BlazorServerアプリの作成 毎度証明書の警告が面倒なのでhttpで開発する 公式のチュートリアル https://dotnet.microsoft.com/learn/aspnet/blazor-tutorial/create $ dotnet new blazorserver -o TestBlazor --no-https # projectフォルダへ移動 $ cd TestBlazor Blazorアプリのカスタマイズ(tips集) DBContextについて 公式のチュートリアルどおりやるとDBContextを直接DIさせる内容だが、随所でNewしたい EFcore関連から調べるとDBFactoryをServiceに追加できるみたいなのでそっちを使う 公式サイト https://docs.microsoft.com/ja-jp/aspnet/core/blazor/blazor-server-ef-core?view=aspnetcore-5.0 appsettings.json "ConnectionStrings": { "MyDbContext": "Persist Security Info=False;User ID=sa;Password=[自分で決めたpass];Initial Catalog=[自分で決めたDB名];Server=localhost" } MyDbContext.cs public class MyDbContext : DbContext { public MyDbContext (DbContextOptions<MyDbContext> options) : base (options) { } public DbSet<Book> Books { get; set; } } Startup.cs // 下記をサービスのところに追加 services.AddDbContextFactory<MyDbContext> (options => options.UseSqlServer (Configuration.GetConnectionString ("MyDbContext")) ); 各所でのContextの使い方は下記 Index.razor @page "/" @inject IDbContextFactory<MyDbContext> DbFactory @teststr <p>@_surnameMessage</p> @code { private string teststr; protected async override Task OnInitializedAsync() { using (var context = DbFactory.CreateDbContext()) { // 処理 teststr = context.Books.FirstOrDefault(b => b.ID == 1); } } } sessionについて 公式サイト  https://docs.microsoft.com/ja-jp/aspnet/core/blazor/state-management?view=aspnetcore-5.0&pivots=server ProtectedSessionStorageを使えと書かれている mvcのときみたいにserviceにaddsessionを書かなくてもセッションは使える模様 (ServerPrerenderedの場合)OnInitializedAsyncでは呼び出せないので注意 Loading処理かいてOnAfterRenderAsyncで呼び出すかプリレンダリングやめるかで回避できる 下記が例、Counterのページで再読み込みしてもクリックの回数がリセットされない Counter.razor @page "/counter" @using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage @inject ProtectedLocalStorage ProtectedLocalStore @if (isConnected) { <p>Current count: <strong>@currentCount</strong></p> <button @onclick="IncrementCount">Increment</button> } else { <p>Loading...</p> } @code { private int currentCount; private bool isConnected;// Sessionからデータ取得できたかどうか protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) {// 初回読み込みのみ実行 isConnected = true; // OnInitializedAsyncでは呼び出せない var result = await ProtectedLocalStore.GetAsync<int>("count"); currentCount = result.Success ? result.Value : 0; StateHasChanged(); } } private async Task IncrementCount() { currentCount++; await ProtectedLocalStore.SetAsync("count", currentCount); } }
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

[VSCode] WSL2を使わず、Remote containerを使う方法

ポイントだけ書きます。 サーバ側 アカウント作成。PCからSSHログインできるようにする dockerを動作するようにする samba serverのcontinerを起動 USERID、GROUPIDは、作成したアカウントのUID,GIDにあわせる。 sudo docker run -it -e USERID=1000 -e GROUPID=1000 \ -p 139:139 -p 445:445 \ -v /home/usesrname:/share \ -d dperson/samba -p \ -u "username;password" \ -s "share;/share;yes;no;no;username" PC側 VSCODEにRemote-conainer プラグインをインストール Docker Disktopをインストール docker context でサーバのdockerにつながるようにする sambaで公開したフォルダをz:\ドライブマウント vscode-remote-try-nodeをz:にgit clone cloneしたフォルダをVSCODEで開く devcontainer.jsonに次の記述を追加 "workspaceFolder": "/workspace", "workspaceMount": "source=/home/masa/vscode-remote-try-node,target=/workspace,type=bind,consistency=cached" コマンドパレットで Open Folder in Containerを実行 参考資料
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Docker Compose で ECS にアプリケーションをデプロイする

初めに 本日 docker-compose を使ってみた記事を書いたので、AWS ECS でも使えないかと調べたところ、ブログで見つけました。いずれ使うときが来るかもしれないのでメモとして残しておきます。 こちらが AWS ECS に Docker Compose でアプリケーションをデプロイする公式ブログになります。 以下の記事も参考にしました。デプロイの詳細な手順について非常にわかりやすく書かれております。 準備 Linux で Docker Compose CLI を使用するための前提条件があります。 1 . Docker Desktop 最新版をダウンロードしインストールしていることが必要です。 Download for Mac Download for Windows あるいは Docker Compose CLI for Linux をインストールしていることが必要です。 2 . AWS アカウントを持っていることが必要です。 こちらのドキュメントを参考にインストールスクリプトを使用します。 curl -L https://raw.githubusercontent.com/docker/compose-cli/main/scripts/install/install_linux.sh | sh AWS コンテキストの生成 このコンテキストにより AWS への認証を行います。aws configure コマンドで認証情報をローカルに登録後、以下のコマンドを実行します。 docker context create ecs myecscontext なお、このコマンド実行時、以下のエラーが発生しました。インスタンスに再ログインしたところ、正常に動作しました。 "docker context create" requires exactly 1 argument. when docker context create ecs myecscontext is executed An existing AWS profile を選択します。 [ec2-user@ip-172-31-39-188 compose]$ docker context create ecs myecscontext ? Create a Docker context using: [Use arrows to move, type to filter] > An existing AWS profile AWS secret and token credentials AWS environment variables ECS へデプロイ 以下の記事で使用したアプリケーションを使用します。 編集前 docker-compose.yml version: '3' services: web: build: . ports: - "8080:5000" volumes: - .:/code redis: image: "redis:alpine" 編集後 docker-compose.yml version: '3' services: web: image: "123456789012.dkr.ecr.ap-northeast-1.amazonaws.com/web-app:latest" ports: - "5000:5000" redis: image: "redis:alpine" flask イメージはビルドではなく、ECR にプッシュしておきます。 ポート番号を 5000:5000 に変更したのは、docker compose up コマンド実行時に以下のエラーが発生したためです。 published port can't be set to a distinct value than container port: incompatible attribute コンテキストを切り替えます。 docker context use myecscontext 現在のコンテキストを確認するには docker context ls コマンドを実行します。 [ec2-user@ip-172-31-39-188 compose]$ docker context ls NAME TYPE DESCRIPTION DOCKER ENDPOINT KUBERNETES ENDPOINT ORCHESTRATOR default moby Current DOCKER_HOST based configuration unix:///var/run/docker.sock swarm myecscontext * ecs コンテキストを切り替えた後ですが、通常の docker コマンドは使用できなくなるようです。例えば docker ps は使えなくなりました。 [ec2-user@ip-172-31-39-188 compose]$ docker ps Command "ps" not available in current context (myecscontext) こういった場合、コンテキストをデフォルトに戻します。 docker context use default compose コマンドで ECS ヘアプリケーションをデプロイします。 docker compose up 以下はコマンド実行中です。完了すると、すべて青色に変わり、ユーザー入力を受け付けるようになります。 デプロイの後、http://NLB の DNS 名:ポート番号 にアクセスします。これは例えば以下のような URL です。 http://compo-loadb-1grujljfn1mmd-06b3d6a23c13c06a.elb.ap-northeast-1.amazonaws.com:5000/ リソース削除には以下のコマンドを実行します。 docker compose down AWS リソースの確認 docker compose up によって新規に作成されたリソースを確認します。VPC、サブネット、セキュリティグループはデフォルトのものが用いられていました。 クラスター クラスター名ですが、ローカルマシンの docker-compose.yml ファイルが存在するディレクトリのディレクトリ名が付けられていました。 サービス flask タスクと redis タスクのサービスがそれぞれ作成されています。 NLB 参考記事
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

"context requires credentials to be passed as environment variables"の対処法

エラー内容 Docker ComposeのAmazon ECSデプロイを試してみた 上の記事を参考にAWSのコンテナ基盤であるECSの概要を理解しようとぽちぽち触っていたところ、contextを作成するために下のコードを実行すると記事にはない選択項目が出現。 $ docker context create ecs myecscontext ↓ > AWS secret and token credentials AWS environment variables 挙動を確認するためと軽い気持ちで2つめのAWS environment variablesを選択したところ, contextの作成に成功したようですが記事のように内容の入力が求められませんでした。 Successfully created ecs context "myecscontext" 気にせず作成したcontextをuseするために下のコードを実行すると悲劇が起きました。 $ docker context use myecscontext docker compose upすると $ docker compose up ↓ context requires credentials to be passed as environment variables 当然何も入力していないcontextなのでこういう挙動なのだなと確認してcontextをdefaultに戻そうとすると $ docker context ls ↓ context requires credentials to be passed as environment variables contextが確認できません。 確認はできなくてもdefaultに戻せれば...と思って実行するも $ docker context use default ↓ context requires credentials to be passed as environment variables 完全にハマってしまいました。コマンド操作をするために元に戻す操作自体ができなくなってしまったのです。 しかしエラー文であるcontext requires credentials to be passed as environment variablesで検索しても全然情報が出てきません。 日本語の情報だけでは解決策がなかったのでついに愛用のMacを詰ませてしまったかと覚悟しましたが、英語のstackoverflowにて同じ悩みを抱えている人を発見。その方も情報が少ないことに悩んでいるようでしたが、回答者の1人が解決策を提示していました。。 Passing environment variables to docker-compose when using ecs context 解決策 $ AWS_SECRET_ACCESS_KEY=dummy AWS_ACCESS_KEY_ID=dummy AWS_DEFAULT_REGION=dummy docker context ls NAME TYPE DESCRIPTION DOCKER ENDPOINT KUBERNETES ENDPOINT ORCHESTRATOR default moby Current DOCKER_HOST based configuration unix:///var/run/docker.sock swarm myecscontext * ecs credentials read from environment $ AWS_SECRET_ACCESS_KEY=dummy AWS_ACCESS_KEY_ID=dummy AWS_DEFAULT_REGION=dummy docker context use default default $ docker context ls NAME TYPE DESCRIPTION DOCKER ENDPOINT KUBERNETES ENDPOINT ORCHESTRATOR default * moby Current DOCKER_HOST based configuration unix:///var/run/docker.sock swarm myecscontext ecs credentials read from environment $ docker context rm myecscontext myecscontext まとめ どうやらAWS environment variablesは文字通りAWSの環境変数を直接ターミナルに打ち込んでデプロイ できる仕組みのようでデタラメでも何かしらを環境変数に代入して実行する必要があったようです。 もちろん何がわからないかもわからない状態で操作してしまった私に非がありますが、どう言ったテンプレートで入力するべき状況で起きているエラーなのかを最低限エラーメッセージとして書いていて欲しかったなと感じました。 今の私には自力でこの解決方法にたどり着くことは不可能だったので、私のように時間を取られる人が1人でも減るように共有したいと思います。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Lima + containerdにおけるEROFS: read-only file system

TL;DR dockerで設定できていたWORKDIRが、containerdでは書き込み権限がないかもしれないことに注意 例 WORKDIR /usr/local/app: Linuxディレクトリ構造のベーシックに倣って配置(って考えたんだと思う) serverless-webpack利用時、rimrafによる一時ファイルの削除が発生 EROFS発生 単に、WORKDIR /app等書き込み権限があるディレクトリに配置すればOK Lima起因なのか、containerd起因なのかは未調査。Rootless関連な気もする。 知ってる人教えてほしいです 経緯 Docker Desktop有料化に伴い、そのほかの選択肢を検討 nttlabsのLima + nerdctlの記事を発見 その時手元にあり、仕事でも使っている以下の構成のdocker-composeで実験してみることに hasura (って何?: Hasura) hasura/graphql-engine:v2.0.8.cli-migrations-v2 postgres (みなさんご存知: PostgreSQL) postgres:12.6 hasura_actions (用途: Actions, Event Triggers, Scheduled Triggers) serverless template: aws-nodejs-typescript serverless-webpack serverless-offline lima nerdctl compose -f docker-compose.yaml upで起動を試す Error: EROFS: read-only file system, rmdir '/usr/local/hasura-actions/.webpack' 発生。serverlessコンテナの起動に失敗する エラー全文 hasura_actions_1 | Error --------------------------------------------------- hasura_actions_1 | hasura_actions_1 | Error: EROFS: read-only file system, rmdir '/usr/local/hasura-actions/.webpack' hasura_actions_1 | at Object.rmdirSync (fs.js:912:10) hasura_actions_1 | at rmdirSync (/usr/local/hasura-actions/node_modules/fs-extra/lib/remove/rimraf.js:264:13) hasura_actions_1 | at Object.rimrafSync (/usr/local/hasura-actions/node_modules/fs-extra/lib/remove/rimraf.js:243:7) hasura_actions_1 | at processConfig (/usr/local/hasura-actions/node_modules/serverless-webpack/lib/validate.js:205:13) hasura_actions_1 | at ServerlessWebpack.validate (/usr/local/hasura-actions/node_modules/serverless-webpack/lib/validate.js:275:14) hasura_actions_1 | From previous event: hasura_actions_1 | at Object.webpack:validate:validate [as hook] (/usr/local/hasura-actions/node_modules/serverless-webpack/index.js:156:63) hasura_actions_1 | at PluginManager.invoke (/usr/local/hasura-actions/node_modules/serverless/lib/classes/PluginManager.js:576:20) hasura_actions_1 | at PluginManager.spawn (/usr/local/hasura-actions/node_modules/serverless/lib/classes/PluginManager.js:598:16) hasura_actions_1 | at ServerlessWebpack.prepareOfflineInvoke (/usr/local/hasura-actions/node_modules/serverless-webpack/lib/prepareOfflineInvoke.js:15:42) hasura_actions_1 | at processImmediate (internal/timers.js:464:21) hasura_actions_1 | From previous event: hasura_actions_1 | at Object.before:offline:start [as hook] (/usr/local/hasura-actions/node_modules/serverless-webpack/index.js:177:12) hasura_actions_1 | at PluginManager.invoke (/usr/local/hasura-actions/node_modules/serverless/lib/classes/PluginManager.js:576:20) hasura_actions_1 | at PluginManager.run (/usr/local/hasura-actions/node_modules/serverless/lib/classes/PluginManager.js:634:18) hasura_actions_1 | at Serverless.run (/usr/local/hasura-actions/node_modules/serverless/lib/Serverless.js:431:5) hasura_actions_1 | at /usr/local/hasura-actions/node_modules/serverless/scripts/serverless.js:685:9 hasura_actions_1 | hasura_actions_1 | For debugging logs, run again after setting the "SLS_DEBUG=*" environment variable. hasura_actions_1 | hasura_actions_1 | Get Support -------------------------------------------- hasura_actions_1 | Docs: docs.serverless.com hasura_actions_1 | Bugs: github.com/serverless/serverless/issues hasura_actions_1 | Issues: forum.serverless.com hasura_actions_1 | hasura_actions_1 | Your Environment Information --------------------------- hasura_actions_1 | Operating System: linux hasura_actions_1 | Node Version: 14.17.6 hasura_actions_1 | Framework Version: 2.47.0 (local) hasura_actions_1 | Plugin Version: 5.4.0 hasura_actions_1 | SDK Version: 4.2.3 hasura_actions_1 | Components Version: 3.12.0 hasura_actions_1 | 調査 検索したクエリを並べますが、以下で答えがみつからず。 lima nerdctl compose EROFS containerd EROFS containerd webpack rimraf webpack rimraf EROFS まあエラー読めば明らかに対象ディレクトリに書き込み権限がないことはわかるのですが、思ったよりこのエラーに出くわす人・記事がいない。 ベーシックなDockerfileの書き方を漁っているうちに、「あれ、みんなWORKDIR /hogeあたりに設定してるな」と気づき、Dockerfileを書き換えたところ動きました。 3, 4時間調査に使って同じ症状の人に辿り着かなかったので結構マイナーな可能性はありますが、後続に苦しむ人がいる可能性を考えて書き残します。 おわりに しばらくぶりの記事でした。 サラッと流しましたが、Hasura + serverlessの環境ってほとんど検索ヒットしないので、そこらへんの記事も書きたい。このスタックでサービスリリースしていたりもするので。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

lima + containerdにおけるEROFS: read-only file system

TL;DR dockerで設定できていたWORKDIRが、containerdでは書き込み権限がないかもしれないことに注意 例 WORKDIR /usr/local/app: Linuxディレクトリ構造のベーシックに倣って配置(って考えたんだと思う) serverless-webpack利用時、rimrafによる一時ファイルの削除が発生 EROFS発生 単に、WORKDIR /app等書き込み権限があるディレクトリに配置すればOK Lima起因なのか、containerd起因なのかは未調査。Rootless関連な気もする。\ 知ってる人教えてほしいです 経緯 Docker Desktop有料化に伴い、そのほかの選択肢を検討 nttlabsのLima + nerdctlの記事を発見 その時手元にあり、仕事でも使っている以下の構成のdocker-composeで実験してみることに hasura (って何?: Hasura) hasura/graphql-engine:v2.0.8.cli-migrations-v2 postgres (みなさんご存知: PostgreSQL) postgres:12.6 hasura_actions (用途: Actions, Event Triggers, Scheduled Triggers) serverless template: aws-nodejs-typescript serverless-webpack serverless-offline lima nerdctl compose -f docker-compose.yaml upで起動を試す Error: EROFS: read-only file system, rmdir '/usr/local/hasura-actions/.webpack' 発生。serverlessコンテナの起動に失敗する エラー全文 hasura_actions_1 | Error --------------------------------------------------- hasura_actions_1 | hasura_actions_1 | Error: EROFS: read-only file system, rmdir '/usr/local/hasura-actions/.webpack' hasura_actions_1 | at Object.rmdirSync (fs.js:912:10) hasura_actions_1 | at rmdirSync (/usr/local/hasura-actions/node_modules/fs-extra/lib/remove/rimraf.js:264:13) hasura_actions_1 | at Object.rimrafSync (/usr/local/hasura-actions/node_modules/fs-extra/lib/remove/rimraf.js:243:7) hasura_actions_1 | at processConfig (/usr/local/hasura-actions/node_modules/serverless-webpack/lib/validate.js:205:13) hasura_actions_1 | at ServerlessWebpack.validate (/usr/local/hasura-actions/node_modules/serverless-webpack/lib/validate.js:275:14) hasura_actions_1 | From previous event: hasura_actions_1 | at Object.webpack:validate:validate [as hook] (/usr/local/hasura-actions/node_modules/serverless-webpack/index.js:156:63) hasura_actions_1 | at PluginManager.invoke (/usr/local/hasura-actions/node_modules/serverless/lib/classes/PluginManager.js:576:20) hasura_actions_1 | at PluginManager.spawn (/usr/local/hasura-actions/node_modules/serverless/lib/classes/PluginManager.js:598:16) hasura_actions_1 | at ServerlessWebpack.prepareOfflineInvoke (/usr/local/hasura-actions/node_modules/serverless-webpack/lib/prepareOfflineInvoke.js:15:42) hasura_actions_1 | at processImmediate (internal/timers.js:464:21) hasura_actions_1 | From previous event: hasura_actions_1 | at Object.before:offline:start [as hook] (/usr/local/hasura-actions/node_modules/serverless-webpack/index.js:177:12) hasura_actions_1 | at PluginManager.invoke (/usr/local/hasura-actions/node_modules/serverless/lib/classes/PluginManager.js:576:20) hasura_actions_1 | at PluginManager.run (/usr/local/hasura-actions/node_modules/serverless/lib/classes/PluginManager.js:634:18) hasura_actions_1 | at Serverless.run (/usr/local/hasura-actions/node_modules/serverless/lib/Serverless.js:431:5) hasura_actions_1 | at /usr/local/hasura-actions/node_modules/serverless/scripts/serverless.js:685:9 hasura_actions_1 | hasura_actions_1 | For debugging logs, run again after setting the "SLS_DEBUG=*" environment variable. hasura_actions_1 | hasura_actions_1 | Get Support -------------------------------------------- hasura_actions_1 | Docs: docs.serverless.com hasura_actions_1 | Bugs: github.com/serverless/serverless/issues hasura_actions_1 | Issues: forum.serverless.com hasura_actions_1 | hasura_actions_1 | Your Environment Information --------------------------- hasura_actions_1 | Operating System: linux hasura_actions_1 | Node Version: 14.17.6 hasura_actions_1 | Framework Version: 2.47.0 (local) hasura_actions_1 | Plugin Version: 5.4.0 hasura_actions_1 | SDK Version: 4.2.3 hasura_actions_1 | Components Version: 3.12.0 hasura_actions_1 | 調査 検索したクエリを並べますが、以下で答えがみつからず。 lima nerdctl compose EROFS containerd EROFS containerd webpack rimraf webpack rimraf EROFS まあエラー読めば明らかに対象ディレクトリに書き込み権限がないことはわかるのですが、思ったよりこのエラーに出くわす人・記事がいない。 ベーシックなDockerfileの書き方を漁っているうちに、「あれ、みんなWORKDIR /hogeあたりに設定してるな」と気づき、Dockerfileを書き換えたところ動きました。 3, 4時間調査に使って同じ症状の人に辿り着かなかったので結構マイナーな可能性はありますが、後続に苦しむ人がいる可能性を考えて書き残します。 おわりに しばらくぶりの記事でした。 サラッと流しましたが、Hasura + serverlessの環境ってほとんど検索ヒットしないので、そこらへんの記事も書きたい。このスタックでサービスリリースしていたりもするので。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Docker Compose を使ってみた

インストール 以下のコマンドを実行し docker-compose コマンドをインストールします。 sudo curl -L https://github.com/docker/compose/releases/download/1.16.1/docker-compose-`uname -s`-`uname -m` \ -o /usr/local/bin/docker-compose 実行権限を付与します。 sudo chmod +x /usr/local/bin/docker-compose 正常にインストールされたことを確認します。 [ec2-user@ip-172-31-46-239 ~]$ docker-compose --version docker-compose version 1.16.1, build 6d1ac21 docker-compose.yml の作成 作業ディレクトリを作成し、以下の手順はすべてこのディレクトリで行います。 mkdir compose_test cd compose_test 次の 2 つのコンテナを作成します。 Web アプリケーション用の Flask コンテナ アクセスカウンタ用の Redis コンテナ 以下のファイルを作成します。 app.py from flask import Flask from redis import Redis app = Flask(__name__) redis = Redis(host='redis', port=6379) @app.route('/') def hello(): count = redis.incr('hits') return 'Hello World! I have been seen {} times.\n'.format(count) if __name__ == "__main__": app.run(host="0.0.0.0", debug=True) requirements.txt flask redis 次に Dockerfile を作成します。 Dockerfile FROM python ADD . /code WORKDIR /code RUN pip install -r requirements.txt CMD ["python", "app.py"] 次に docker-compose.yml を作成します。 web サービスは Dockerfile で作成するイメージから構築する redis サービスは Docker Hub から取得するイメージから構築する コンテナの公開用ポート 5000 を、ホストマシンのポート 8080 にポートフォワードする ホストマシンの compose_test ディレクトリを コンテナ内の /code ディレクトリにマウントする docker-compose.yml version: '3' services: web: build: . ports: - "8080:5000" volumes: - .:/code redis: image: "redis:alpine" 以下のコマンドを実行し、コンテナを起動します(バックグラウンドで実行する場合は -d オプションを付けます)。 docker-compose up アプリケーションにアクセスする もう一つターミナルを開いてアクセスします。 [ec2-user@ip-172-31-46-239 compose_test]$ curl http://localhost:8080 Hello World! I have been seen 1 times. app.py を編集したい場合、compose_test ディレクトリと /code ディレクトリは同期しているので、ローカルで app.py を編集すれば、再度 docker-compose up コマンドを実行することなく、変更がアプリケーションに反映されます。 参考記事
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

WSLでGUIアプリを実行する

1.この記事の内容 Windows 11 ビルド22000以降で,LinuxのGUIアプリを実行できるようになったらしいので,試してみました. GUIアプリの起動時にcannot open displayのエラーが出て対策試行の経緯も記載しています. 普段はWSLからDockerを起動して作業していますので,コンテナ上からGUIアプリ起動まで試します. 1-1.使用環境 Windows11 ビルド PythonのGUI処理の動作を確認 2.Windows 11アップデート 2-1.アップデート前の準備(アップデート要件への対応) 手元の環境では,Windows11へのアップデート要件のうち,TPM 2.0とセキュアブートの2点で引っかかりました. 2-1-1.TPM 2.0 筆者のPCはASUSマザーボード+Indel CPUの構成で,[Motherboard] ASUS マザーボードに Windows 11 をインストールする方法は?に記載の手順で要件をクリアできました. 2-1-2.セキュアブート セキュアブートの設定はWindows 11導入に必要なBIOS/UEFI設定メモに記載の手順で要件をクリアできました. mbr2gptを実行する際には,コマンドプロンプトを管理者権限で起動する必要があります. > mbr2gpt /validate /disk:0 /allowFULLOS MBR2GPT: Attempting to validate disk 0 MBR2GPT: Retrieving layout of disk MBR2GPT: Validating layout, disk sector size is: 512 bytes MBR2GPT: Validation completed successfully > mbr2gpt /convert /disk:0 /allowFULLOS MBR2GPT will now attempt to convert disk 0. If conversion is successful the disk can only be booted in GPT mode. These changes cannot be undone! MBR2GPT: Attempting to convert disk 0 MBR2GPT: Retrieving layout of disk MBR2GPT: Validating layout, disk sector size is: 512 bytes MBR2GPT: Trying to shrink the OS partition MBR2GPT: Creating the EFI system partition MBR2GPT: Installing the new boot files MBR2GPT: Performing the layout conversion MBR2GPT: Migrating default boot entry MBR2GPT: Adding recovery boot entry MBR2GPT: Fixing drive letter mapping MBR2GPT: Conversion completed successfully MBR2GPT: Update WinRE config file MBR2GPT: Before the new system can boot properly you need to switch the firmware to boot to UEFI mode! 2-2.Windows11 アップデート Windows Updateからのアップデートで正常にアップデートできました. 3.Linux GUIアプリを実行する Linux 用 Windows サブシステムで Linux GUI アプリを実行する (プレビュー)の手順にそって,GUIアプリの動作確認を行います. 既にNVIDIA WSL 用 GPU ドライバーのインストールとWSLのインストールは完了していたので,事前準備は既存の WSL インストールのみを行いました. 3-1.WSLをアップデートする PowerShellを管理者として実行して下記コマンドでWSLをアップデートします. > wsl --update > wsl --shutdown 3-2.geditでGUIアプリの起動確認を行う $ sudo apt update $ sudo apt install gedit -y $ export DISPLAY=:0.0 $ gedit test.txt ディスプレイに接続できないというエラーが出ました. 3-4.参考:エラー対策試行錯誤に試行錯誤の内容を列挙しますが,筆者の環境では, 環境変数DISPLAY=:0.0を設定する c:\users\MyUser.wslconfigからguiApplications=falseの設定を削除する ※設定を削除した後は,wsl --shutdownして再起動 の2点の対応で解決しました. 3-3.Dockerコンテナ上からのGUIアプリ起動 これまで使用していたDockerには環境変数やX11環境の設定は考慮していないので,当然ですが,下記の通りエラーが発生しました. # export DISPLAY=:0.0 # xeyes Error: Can't open display: 環境変数DISPLAYとX11環境(/tmp/.X11-unix)があればよいので,docker runの引数に-v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAYを追加して,Dockerコンテナ上からGUIアプリを起動することができました. 3-4.参考:エラー対策試行錯誤 $ gedit test.txt Unable to init server: Could not connect: Connection refused (gedit:8534): Gtk-WARNING **: 06:02:44.554: cannot open display: 他のアプリでも同様か確認(x11アプリで試行) $ sudo apt install x11-apps -y $ gedit test.txt Unable to init server: Could not connect: Connection refused (gedit:417): Gtk-WARNING **: 06:13:00.458: cannot open display: $ xeyes Error: Can't open display: gedit同様にエラーが出た. NVIDIA WSL 用 GPU ドライバーのバージョンを更新してみる. $ nvidia-smi.exe Fri Sep 10 06:15:27 2021 +-----------------------------------------------------------------------------+ | NVIDIA-SMI 465.42 Driver Version: 465.42 CUDA Version: 11.3 | |-------------------------------+----------------------+----------------------+ | GPU Name TCC/WDDM | Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | | | | MIG M. | |===============================+======================+======================| ↓ $ nvidia-smi.exe Fri Sep 10 06:23:48 2021 +-----------------------------------------------------------------------------+ | NVIDIA-SMI 510.06 Driver Version: 510.06 CUDA Version: 11.6 | |-------------------------------+----------------------+----------------------+ | GPU Name TCC/WDDM | Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | | | | MIG M. | |===============================+======================+======================| ... $ gedit test.txt Unable to init server: Could not connect: Connection refused (gedit:26): Gtk-WARNING **: 06:24:52.648: cannot open display: 関係なかった. パッケージをアップグレードしてみる. $ sudo apt upgrade -y ... $ gedit test.txt Unable to init server: Could not connect: Connection refused (gedit:8407): Gtk-WARNING **: 10:15:52.745: cannot open display: 関係なかった. ~/.profile に環境変数DISPLAYを設定する(export DISPLAY=:0.0を追記). $ gedit test.txt Unable to init server: Could not connect: Connection refused (gedit:8503): Gtk-WARNING **: 10:30:08.404: cannot open display: :0.0 関係なかった. wslgでGUIを出そうとしたときに"Error: Can't open display: :0"と言われたときの対処法を参考に,/etc/tmpfiles.d/wslg.conf を作成した. $ gedit test.txt Unable to init server: Could not connect: Connection refused (gedit:125): Gtk-WARNING **: 09:42:57.859: cannot open display: 関係なかった. WSLg System Distroにc:\users\MyUser.wslconfigに [wsl2] guiApplications=false を設定するとGUIアプリケーションサポートをOFFにすることができると書いてあり,まさかと思い確認すると,この設定が記述されていた. 何かの作業の際に設定したと思われるが,設定を削除後,wsl --shutdownでWSLを一度停止して,再起動するとGUIアプリケーション(geditとxeyes)が起動することが確認できた. 環境設定DISPLAY=:0.0の設定は必要な模様. 4.さいごに 色々と試行錯誤をしましたが,結局は筆者の過去の取り組みを悔やむ形となりました. Pythonのmatplotlibからのグラフ出力などのGUI出力も確認ができました(モジュールごとのGUI出力設定は必要). 参考になる方がおられたら幸いです. 5.関連リンク Linux 用 Windows サブシステムで Linux GUI アプリを実行する (プレビュー) [Motherboard] ASUS マザーボードに Windows 11 をインストールする方法は? Windows 11導入に必要なBIOS/UEFI設定メモ Windows11 の WSL2 + WSLg で GUI アプリ実行時に発生するエラー「Error: Can’t open display: 0」の対処方法 wslgでGUIを出そうとしたときに"Error: Can't open display: :0"と言われたときの対処法 Diagnosing "cannot open display" type issues with WSLg WSL 2: Run Graphical Linux Desktop Applications from Windows 10 Bash Shell "Error E233: cannot open display" WSLg System Distro Can I use the new WSLg with Docker?
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Dockerの最新版(20.10.8)でコンテナ内部からhttps通信ができない問題の対策

エラー内容:何が起きたか コンパイル言語であるGoのコードや機能の改修を行いやすくするために、Dockerを用いてGoの環境構築を行っていたところコンテナ内部で謎のネットワークエラーが出た。 行った手順としてはまず、以下のようなDockerfileとdocker-compose.ymlを作成。 Dockerfile FROM golang:latest WORKDIR /path/to/go/project COPY go.mod ./ COPY go.sum ./ RUN go mod download COPY path/to/main.go ./ EXPOSE 8080 docker-compose.yml version: '3' services: app: container_name: go_container image: golang:latest tty: true ports: - "3000:3000" volumes: - /path/to/$GOPATH:/go (※なお、今回の事象はこれと全く同じ構成のdocker-composeでなくとも発生する。 理由は後述) docker-composeを実行 docker-compose up --build -d すると、go mod downlodのところで永遠に処理が終わらない。 別のアプローチ Dockerfileを以下のように変更 Dockerfile FROM golang:latest WORKDIR /path/to/go/project COPY go.mod ./ COPY go.sum ./ RUN go get -u github.com/go-sql-driver/mysql COPY path/to/main.go ./ EXPOSE 8080 go getで取得するモジュールはなんでもOK これを実行すると以下のようなエラーが返ってくる。 (前略) net/http: TLS handshake timeout つまりネットワークが途絶えてしまっている。 後の調査(内容割愛。curlとか)の結果、奇妙なことにhttps通信の場合にだけこのような事象が発生することがわかった。 原因:答えはスタート地点に 原因がわからず数日にわたって調べまくったところ、公式の最新バージョン(20.10.8)リリースノートに以下のような記述を発見。 IMPORTANT Due to net/http changes in Go 1.16, HTTP proxies configured through the \$HTTP_PROXY environment variable are no longer used for TLS (https://) connections. Make sure you also set an $HTTPS_PROXY environment variable for handling requests to https:// URLs. Refer to the HTTP/HTTPS proxy section to learn how to configure the Docker Daemon to use a proxy server. go側のnet/httpの仕様変更に伴って環境変数 $HTTPS_PROXYも自分で設定しなきゃダメだよということ。(かなり大雑把) 灯台下暗しとはまさにこのこと。 これならどのようなDockerfileを書いたところで同じ事象に遭遇するはず。 とはいえ、設定するようなプロキシサーバがなかったため、squidを使用してホスト側にプロキシサーバを建てることに。 対策:環境変数の設定とプロキシサーバの設置 squidのインストール・設定 (僕の利用していた環境はcentos7なので、yumを利用して)squidをインストール sudo yum install -y squid /etc配下にある設定ファイルを編集 /etc/squid/squid.conf # # Recommended minimum configuration: # # Example rule allowing access from your local networks. # Adapt to list your (internal) IP networks from where browsing # should be allowed acl localnet src 10.0.0.0/8 # RFC1918 possible internal network acl localnet src 172.16.0.0/12 # RFC1918 possible internal network acl localnet src 192.168.0.0/16 # RFC1918 possible internal network acl localnet src fc00::/7 # RFC 4193 local private network range acl localnet src fe80::/10 # RFC 4291 link-local (directly plugged) machines acl SSL_ports port 443 acl Safe_ports port 80 # http acl Safe_ports port 21 # ftp acl Safe_ports port 443 # https acl Safe_ports port 70 # gopher acl Safe_ports port 210 # wais acl Safe_ports port 1025-65535 # unregistered ports acl Safe_ports port 280 # http-mgmt acl Safe_ports port 488 # gss-http acl Safe_ports port 591 # filemaker acl Safe_ports port 777 # multiling http acl CONNECT method CONNECT # 以下2行を追記(多分コンテナの方だけでいい) acl name(任意の名前1) src (DockerホストのIP) acl name2(任意の名前2) src (DockerコンテナのIP) # # Recommended minimum Access Permission configuration: # # Deny requests to certain unsafe ports http_access deny !Safe_ports # Deny CONNECT to other than secure SSL ports http_access deny CONNECT !SSL_ports # Only allow cachemgr access from localhost http_access allow localhost manager http_access deny manager # We strongly recommend the following be uncommented to protect innocent # web applications running on the proxy server who think the only # one who can access services on "localhost" is a local user #http_access deny to_localhost # # INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS # # Example rule allowing access from your local networks. # Adapt localnet in the ACL section to list your (internal) IP networks # from where browsing should be allowed # http_access allow localnet http_access allow localhost # 以下2行を追記(こちらも多分コンテナの方ry) # (※name, name2はさきほど定義したもの) http_access allow name http_access allow name2 # http_access allow all # And finally deny all other access to this proxy http_access deny all # Squid normally listens to port 3128 http_port 3128 # Uncomment and adjust the following to add a disk cache directory. #cache_dir ufs /var/spool/squid 100 16 256 # Leave coredumps in the first cache dir coredump_dir /var/spool/squid # # Add any of your own refresh_pattern entries above these. # refresh_pattern ^ftp: 1440 20% 10080 refresh_pattern ^gopher: 1440 0% 1440 refresh_pattern -i (/cgi-bin/|\?) 0 0% 0 refresh_pattern . 0 20% 4320 (squidのデフォルトのポート番号は3128。今回はとくに変更しない。) コンテナのIDがわからない場合は、コンテナ内部に入り以下のコマンドで確認 hostname -i 参考:コンテナのIPを確認する方法 開始 sudo systemctl start squid 次はdocker側の設定 Docker側、環境変数$HTTP(S)_PROXYの設定 Docker公式の設定ページに従って環境変数を設定。 sudo mkdir -p /etc/systemd/system/docker.service.d /etc/systemd/system/docker.service.d Environment="HTTP_PROXY=(squidを設置したホストのIP):3128" Environment="HTTPS_PROXY=(squidを設置したホストのIP):3128" ついでに、dockerを利用するユーザーのホームディレクトにconfig.jsonを設置。 公式ページの設定ガイドラインはこちら ~/.docker/config.json { "proxies": { "default": { "httpProxy": "(squidホスト):3128", "httpsProxy": "(squidホスト):3128" } } } 書いたらDockerを再起動。 sudo systemctl restart docker 再起動するとコンテナが止まってしまうためコンテナをstartするのを忘れないように。 自分はそれで気づかずにホストでhttpsの検証してぬか喜びしてしまった 確認 コンテナ内部でcurlコマンドを使い検証。 alpine使ってる人とかでcurlできない人はインストールするか、apk updateでもかけてみるのがよし。 crul https://google.com <HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8"> <TITLE>301 Moved</TITLE></HEAD><BODY> <H1>301 Moved</H1> The document has moved <A HREF="https://www.google.com/">here</A>. </BODY></HTML> HTMLが返ってきたらOK。 この状態になればgo getやgo mod downloadなどのコマンドも通る。 総括 最新版(20.10.8)のDockerはコンテナ内部からhttps通信を行うためにプロキシが必要。 20.10.7などの直前バージョンを使おうとしても、他モジュールが20.10.8でくっついてきてしまったり、そもそものgoの仕様変更だったりという事情で結局この事象から逃れられなかった。 また、最初からhttp通信はできていたが、$HTTP_PROXYのデフォルト値は見つけられなかった。(echoだと空行) もっと簡単にできたなどあれば方法教えてください。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む