LXD で新しくサーバーとして使用する仮想マシンを作成した際のメモです。
- サーバー
- HPE ProLiant MicroServer Gen10 Plus
- CPU
- 4コア
- メモリー
- 32GB
- OS
- Ubuntu Server 24.04 LTS 64Bit
パッケージ | バージョン |
---|---|
lxd | 5.21.2-084c8c8 |
コンテンツ
新しい仮想マシンを作成
以下のコマンドでイメージサーバーの一覧を表示します。
lxc remote list
以下のコマンドでイメージサーバー ubuntu で利用可能なイメージの一覧を表示します。
lxc image list ubuntu:
以下のコマンドで新しい仮想マシンを作成します。
lxc init <IMAGE_SERVER>:<IMAGE_NAME> <INSTANCE_NAME> [FLAGS]
lxc init ubuntu:24.04 <CONTAINER_NAME> --device root,size=20GiB --config limits.cpu=2 --config limits.memory=4GiB
- –vm
- コンテナではなく VM を作成する
- –device root,size=20GiB
- メインドライブのサイズを20GiBに設定
- –config limits.cpu=2
- CPU コア数を 2 に設定
- –config limits.memory=4GiB
- メモリサイズを 4GiB に設定
ネットワークをブリッジ接続に変更
以下のコマンドでデフォルトの nat 接続からブリッジ接続に変更します。(物理ネットワークデバイスが eno1 の場合)
lxc config device remove <CONTAINER_NAME> eth0
lxc config device add <CONTAINER_NAME> eth0 nic nictype=macvlan parent=eno1 name=eth0
デフォルトユーザー名の変更
作成したインスタンスを起動して、以下のコマンドでデフォルトのユーザー名 ubuntu を任意の <NEW_USERNAME> に変更します。
lxc exec <CONTAINER_NAME> -- usermod -l <NEW_USERNAME> -d /home/<NEW_USERNAME> -m ubuntu
以下のコマンドでグループ名も変更します。
lxc exec <CONTAINER_NAME> -- groupmod -n <NEW_USERNAME> ubuntu
以下のコマンドでパスワードを変更します。
lxc exec <CONTAINER_NAME> -- passwd <NEW_USERNAME>
以下のコマンドで sudo ユーザーの設定も変更します。
lxc exec <CONTAINER_NAME> -- bash -c "echo '<NEW_USERNAME> ALL=(ALL) ALL' > /etc/sudoers.d/<NEW_USERNAME>"
以下のコマンドで ubuntu に sudo 権限を与えているファイルを削除します。
lxc exec <CONTAINER_NAME> -- rm /etc/sudoers.d/90-cloud-init-users
以下のコマンドで新しいユーザーの SSH 公開鍵を登録します。
lxc exec <CONTAINER_NAME> -- bash -c "echo 'ssh-ed25519 AAAAC... newusername@example.com' > /home/<NEW_USERNAME>/.ssh/authorized_keys"
Cloud-Init を無効化
このまま再起動すると Cloud-Init が再度 ubuntu ユーザーを作成してしまうので、Cloud-Init を以下のコマンドで無効化します。
lxc exec <CONTAINER_NAME> -- touch /etc/cloud/cloud-init.disabled
lxc exec <CONTAINER_NAME> -- systemctl disable cloud-init
以下のコマンドで Cloud-Init を削除します。
lxc exec <CONTAINER_NAME> -- apt remove --purge -y cloud-init
以下のコマンドで設定ファイルを削除します。
lxc exec <CONTAINER_NAME> -- rm -rf /var/lib/cloud/
SSH サーバーの設定を変更
作成した仮想マシンに SSH で接続し、SSH サーバーの設定を変更します。
sudo vim /etc/ssh/sshd_config
以下を変更・追加します。
Port 2222
LogLevel VERBOSE
PermitRootLogin no
PasswordAuthentication no
MaxAuthTries 3
MaxSessions 1
PubkeyAuthentication yes
PermitEmptyPasswords no
X11Forwarding no
AllowUsers <NEW_USERNAME>
以下のコマンドでファイアウォールの設定を変更します。
sudo ufw allow 2222/tcp
sudo ufw enable
以下のコマンドで SSH サーバーを再起動して設定を反映します。
sudo systemctl restart ssh
新しいポートで接続できない場合は一度仮想マシンを再起動します。
sudo reboot
IP アドレスを変更
以下のコマンドで接続されているネットワークインターフェースを確認します。
ip link show
netplan の設定ファイルを変更して静的 IP を割り当てます。
sudo vim /etc/netplan/50-cloud-init.yaml
network:
version: 2
ethernets:
eth0:
dhcp4: no
addresses:
- 192.168.1.100/24
gateway4: 192.168.1.1
nameservers:
addresses:
- 192.168.1.1
インスタンスを再起動
設定を終えたら以下のコマンドで仮想マシンを再起動します。
lxc exec <CONTAINER_NAME> -- reboot