LoginSignup
3
1

More than 5 years have passed since last update.

dnsmasq でローカルホスト内に heroku のようなサブドメイン設定を実現する

Posted at

「heroku のようなサブドメイン設定」というのは、こういうやつです。

ドメイン IP
localhost.com 127.0.0.1
a.localhost.com 127.0.0.1
b.localhost.com 127.0.0.1
c.localhost.com 127.0.0.1

Dnsmasq を使うと、割と簡単に実現することができました。
(最初 bind でやろうとしたけど設定ファイルの書き方が難しくて挫折しました…。)

やり方

下記はニフティクラウド + Ubuntu 14.04 での設定例になります。

まず、名前解決に利用するネームサーバーを 127.0.0.1 に設定します。
(ニフティクラウドのサーバーの場合は、デフォルトで下記の設定になっていました。)

# vi /etc/resolv.conf
# cat /etc/resolv.conf 
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
nameserver 127.0.0.1
search localdomain

dnsmasq のインストール。

# apt-get install -y dnsmasq
(略)
dnsmasq: failed to create listening socket for port 53: Address already in use
   ...fail!
invoke-rc.d: initscript dnsmasq, action "start" failed.
Processing triggers for libc-bin (2.19-0ubuntu6.7) ...
Processing triggers for ureadahead (0.100.0-16) ...

ニフティクラウドのサーバーではデフォルトでローカルに bind が起動し 127.0.0.1 にバインドして 53 ポートを LISTEN しているため、dnsmasq が起動に失敗してしましました。
なので、bind を落としておきます。

# service bind9 stop

次に、dnsmasq の設定を書きます。
名前解決にはデフォルトで Google のものを使い、localhost.com の場合だけ冒頭にあげたような名前解決ができるようにする設定です。

# vi /etc/dnsmasq.d/localhost.com
# cat /etc/dnsmasq.d/localhost.com
server=8.8.8.8
server=8.8.4.4
address=/localhost.com/127.0.0.1

最後に dnsmasq を起動します。

# service dnsmasq start

動作確認

A レコードを dig してみると、実現したい設定になっていることが分かります。

# dig -t A localhost.com | grep -A 1 'ANSWER SECTION'
;; ANSWER SECTION:
localhost.com.          0       IN      A       127.0.0.1

# dig -t A a.localhost.com | grep -A 1 'ANSWER SECTION'
;; ANSWER SECTION:
a.localhost.com.        0       IN      A       127.0.0.1

# dig -t A b.localhost.com | grep -A 1 'ANSWER SECTION'
;; ANSWER SECTION:
b.localhost.com.        0       IN      A       127.0.0.1

# dig -t A c.localhost.com | grep -A 1 'ANSWER SECTION'
;; ANSWER SECTION:
c.localhost.com.        0       IN      A       127.0.0.1

当然ながら ping もすべて 127.0.0.1 に届きます。

# ping localhost.com
PING localhost.com (127.0.0.1) 56(84) bytes of data.
(略)

# ping a.localhost.com
PING a.localhost.com (127.0.0.1) 56(84) bytes of data.
(略)

# ping b.localhost.com                                                                                                                                                PING b.localhost.com (127.0.0.1) 56(84) bytes of data.
(略)

# ping c.localhost.com
PING c.localhost.com (127.0.0.1) 56(84) bytes of data.
(略)

一応、外部のドメインにも ping できることを確認しておきます。

# ping www.google.com
PING www.google.com (172.217.27.36) 56(84) bytes of data.
(略)

まとめ

ローカル環境内に「heroku のようなサブドメイン設定」を実現することができました。
tumblr のようにサブドメインを扱うようなアプリを開発する際に便利な気がします。

参考資料

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