If your Markdown file is to be displayed in a repo on bitbucket.org, you should add [TOC] at the location where you want your table of contents. It will then be auto-generated. More info here:
https://confluence.atlassian.com/bitbucket/add-a-table-of-contents-to-a-wiki-221451163.html