Skip to content

Instantly share code, notes, and snippets.

@pulecp
Created August 8, 2017 07:19
Show Gist options
  • Save pulecp/b2c44090d2461935a14aeb4e6cf34b40 to your computer and use it in GitHub Desktop.
Save pulecp/b2c44090d2461935a14aeb4e6cf34b40 to your computer and use it in GitHub Desktop.
Change MongoDB default port
#!/bin/bash
echo 'DISABLE PUPPET ON ALL MONGO MACHINES AT FIRST'
old_port=27017
new_port=27018
# This script change default port of mongod instance and keep old port
# redirected to a new port
puppet agent --disable 'kayn: changing default mongod port'
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -I PREROUTING -p tcp --dport $old_port -j REDIRECT --to-port $new_port
# previous redirect logs a lot of stuff!
mv /etc/rsyslog.d/iptables.conf /tmp/
systemctl restart rsyslog
sed -i "s/$old_port/$new_port/" /etc/mongod.conf
systemctl restart mongod
echo 'Now open mongo shell on primary and change the port by in following steps (if you are on primary, you need to stepDown before by `rs.stepDown()`:
# load configuration
cfg = rs.conf()
# use proper ID instead of X and check if the name matchs with the member you are changing a port
cfg.members[X].host
# change port by
cfg.members[X].host = "mongo0X:27018"
# reload configuration
rs.reconfig(cfg)
# now check the replicaSet status and wait until changed member is synced (journal on arbiter can start to grow rapidly, please watch the size by `watch -n60 du -sh /var/lib/mongodb/journal`. If it will grow, you need to stop mongo, remove everything in /var/lib/mongodb/ and start arbiter again).
rs.status()'
echo "Once the mongos routers and replica sets are reconfigured properly in puppet, remove the redirect firewall rules by:
iptables -t nat -D PREROUTING -p tcp --dport $old_port -j REDIRECT --to-port $new_port
echo 0 > /proc/sys/net/ipv4/ip_forward
and enable puppet"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment