If you're only going to live somewhere for a few years, you might want to consider renting rather than buying a home.
Let's say you buy a house and then have to sell it within two to three years. The various buying and selling costs alone will probably amount to a significant amount of money. Will the house have appreciated enough to cover those costs? It's possible, but not likely. Heck, just as with the stock market, over a short period of time, the value of your investment may even decline.
Also, remember that in the first years when you're paying off a traditional mortgage, your payments are mostly going toward interest, not toward building equity (paying off the principal balance). So, after living in the house for only a few years, you'll probably technically own just a tiny part of it.
Renting is always an option to consider. It's true that mortgage interest is tax-deductible, and it can be cost-effective to own rather than rent. But if you're renting a place for considerably less than you'd have to cough up in mortgage payments, you might invest the difference and profit through stocks rather than real estate.